二叉树 最小公共父节点

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:57   2436   0
#include <list>
#include <iostream>
#include <algorithm>
#include <gtest\gtest.h>
#include <string>
using namespace std;
struct TreeNode{
 char value;
 TreeNode * lchild;
 TreeNode * rchild;
 TreeNode(char val, TreeNode *lch, TreeNode * rch) :value(val), lchild(lch), rchild(rch){}
};

void createTree(TreeNode **pHead, TreeNode **n1, TreeNode **n2){
 TreeNode *pF = new TreeNode('F', nullptr, nullptr);
 TreeNode *pG = new TreeNode('G', nullptr, nullptr);
 TreeNode *pH = new TreeNode('H', nullptr, nullptr);
 TreeNode *pI = new TreeNode('I', nullptr, nullptr);

 TreeNode *pD = new TreeNode('D', pF, pG);
 TreeNode *pE = new TreeNode('E', pH, pI);

 TreeNode *pB = new TreeNode('B', pD, pE);
 TreeNode *pC = new TreeNode('C', nullptr, nullptr);

 TreeNode *pA = new TreeNode('A', pB, pC);
 *pHead = pA;
 *n1 = pH;
 *n2 = pF;
}




bool getNodePath(TreeNode *pHead, TreeNode* pNode, list<TreeNode*> &path){
 if (pHead == nullptr)
  return false;
 if (pHead == pNode){
  path.push_back(pHead);
  return true;
 }
 //bool found = false;
 path.push_back(pHead);

 if (getNodePath(pHead->lchild, pNode, path) || getNodePath(pHead->rchild, pNode, path))
 {
  return true;
 }

 path.pop_back();

 return false;


}

int add(int x, int y){
 return x + y;
}
void deleteTree(TreeNode *pHead){
 if (pHead == nullptr)
  return;
 deleteTree(pHead->lchild);
 deleteTree(pHead->rchild);
 delete pHead;
 pHead = nullptr;
}
in tmain(){
TreeNode *phead, *pH, *pF;
 createTree(&phead, &pH, &pF);
 list<TreeNode*> path1;
 getNodePath(phead, pH, path1);
 for_each(path1.begin(), path1.end(), [](const TreeNode * node){cout << node->value << " "; });
 cout << endl;
 list<TreeNode*> path2;
 getNodePath(phead, pF, path2);
 for_each(path2.begin(), path2.end(), [](const TreeNode * node){cout << node->value << " "; });
 cout << endl;

 deleteTree(phead);

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP