to find the lowest common ancestor of two nodes in a tree
Given a tree and two nodes, the lowest common ancestor node in the tree is solved for these two nodes. (Sword refers to an offer)
idea:
Traverse the tree from the root node until the node you want to find saves the path from the root node to the node you are looking for. The tree is traversed two times, that is, the root node is saved to the two paths of the two nodes to find, and then the last intersection of two paths can be obtained. C + + code implementation:
#include <iostream> #include <vector> #include <list> using namespace std;
typedef struct treenode{int data;
struct TreeNode *leftchild;
struct TreeNode *rightchild;
}treenode, *bitree;
BOOL Getnodepath (treenode* proot, int data, list<bitree> &path) {if (Proot = NULL) {return false;
} if (proot->data = = data) {return true;
} path.push_back (Proot);
BOOL found = false;
if (!found) {found = Getnodepath (proot->leftchild, data, path);
} if (!found) {found = Getnodepath (proot->rightchild, data, path);
} if (!found) {path.pop_back ();
return found; } bitree Getlastcommonnode (list<bitree> &path1, list<bitree> &path2) {List<BiTree>::const_
Iterator I1 = Path1.begin ();
List<bitree>::const_iterator i2 = Path2.begin ();
Bitree pLast = NULL; for (; I1!=path1.end () && i2!=path2.end ();) {if (*I1) = = *i2) {pLast = *i1;
} ++i1;
++i2;
return pLast;
} bitree getlastcommonparent (treenode* proot, int data1, int data2) {if (Proot = null) {return null;
} list<bitree> path1, path2;
Getnodepath (Proot, data1, path1);
Getnodepath (Proot, data2, path2);
Return Getlastcommonnode (path1, path2);
int Creattree (Bitree &t) {int data;
CIN >> data;
if (data = = 1) {T = NULL;
return 0;
}else{T = (bitree) malloc (sizeof (TreeNode));
T->data = data;
Creattree (T->leftchild);
Creattree (T->rightchild);
return 0;
int main (int argc, const char * argv[]) {//Insert code here ...
Bitree T, result;
int data1, data2;
Creattree (T);
CIN >> data1 >> data2;
result = Getlastcommonparent (T, data1, data2);
cout << result->data << Endl;
return 0;
}