The Write Program finds the closest common ancestor of the two nodes in a binary tree.
This question is discussed in two cases:
In the first case, the node does not have a pointer to the parent node.
In the second case, there is a pointer to the parent node.
Let's first look at the first case. The node does not have a pointer to the parent node.
We can use brute force to search for each node.
If there are two known nodes, we can continue searching along the left and right subtree.
If the tree can be found, we can continue searching along the left subtree. If a subtree can be found, we will
Search along the right subtree. No two subtree can be found.
Code:
Struct treenode {<PRE name = "code" class = "html"> struct treenode {int data; treenode * leftchild; treenode * rightchild; treenode * parent ;}; // use the parent node bool compute (const treenode * vnodea, const treenode * vnodeb, treenode * vancestor) {If (isfather (vnodea, vnodeb) {vancestor = vnodea; return true;} If (isfather (vnodeb, vnodea) {vancestor = vnodeb; return true;} treenode * parent = vnodea-> parent; while (true) {If (isfather (parent, vnodeb) {vancestor = parent; return true;} parent = parent-> parent;} return false ;}
The second case is relatively simple. If there is a pointer to the parent node, we can search for
Parent node, and then determine whether it is the parent node of the second known node.
Code:
Struct treenode {int data; treenode * leftchild; treenode * rightchild; treenode * parent;}; // use the parent node bool compute (const treenode * vnodea, const treenode * vnodeb, treenode * vancestor) {If (isfather (vnodea, vnodeb) {vancestor = vnodea; return true;} If (isfather (vnodeb, vnodea) {vancestor = vnodeb; return true;} treenode * parent = vnodea-> parent; while (true) {If (isfather (parent, vnodeb) {vancestor = parent; return true ;} parent = parent-> parent;} return false ;}
019 write a program to find the nearest common ancestor of the two nodes in a binary tree (keep it up)