#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);
}
|