Minimum common ancestor of two nodes in the tree

Source: Internet
Author: User
Case 1: The binary sorting tree.Idea: Compare the source node with the input two nodes. If the current node value is greater than the value of the two nodes, the lowest ancestor must be in the left subtree, the next step is to traverse the left subnode of the current node. If the value of the current node is smaller than the value of the two nodes, the lowest ancestor must be in the right subtree. Therefore, the next step is to traverse the right subtree of the current node. If the current node is exactly one of the two input nodes, it indicates that one of the two nodes is the ancestor of the other, and the output is the parent node of the current node.
/* Common Ancestor series of Binary Trees 1. binary Tree is a binary sorting tree by rowandjj2014/8/20 */# include <iostream> using namespace STD; typedef struct _ node _ {int data; struct _ node _ * left; struct _ node _ * right;} bnode, * pbnode, * ptree; // constructs a binary tree void create (ptree * PT) {int data; CIN> data in the FIFO manner; if (Data =-1) {return;} * PT = (pbnode) malloc (sizeof (bnode); If (! Pt) {exit (-1) ;}( * PT)-> DATA = data; (* PT)-> left = NULL; (* PT)-> right = NULL; create (& (* PT)-> left); Create (& (* PT)-> right);} pbnode findancestor (ptree PT, pbnode pnode1, pbnode pnode2) {If (Pt = NULL | pnode1 = NULL | pnode2 = NULL) {return NULL;} If (Pt = pnode1 | Pt = pnode2) // at least one of the input nodes is the root node. In this case, no ancestor {return NULL;} pbnode pparent = NULL; int pdata1 = pnode1-> data; int pdata2 = pnode2-> data; If (pdata1> pdata2) {Int temp = pdata1; pdata1 = pdata2; pdata2 = temp;} while (PT! = NULL) {If (Pt-> data <pdata1) // the current node is smaller than the two input nodes {// pparent = PT In the right subtree; PT = Pt-> right;} else if (Pt-> DATA> pdata2) // The current node is larger than the two input nodes {// note that pparent = pt; Pt = Pt-> left;} in the left subtree ;} else if (Pt = pnode1 | Pt = pnode2) // the current node is exactly one of the input nodes, indicating that one of the two input nodes is another ancestor {return pparent ;} else // the current node value {return PT ;}} return NULL;} void display (ptree pt) {If (Pt = NULL) {return ;} if (Pt-> left) {display (Pt-> left) ;}cout <Pt-> data <""; if (Pt-> right) {display (Pt-> right) ;}} int main () {ptree Pt = NULL; Create (& pt); display (PT ); cout <"\ n"; pbnode n = (pbnode) malloc (sizeof (bnode); If (! N) {exit (-1);} n-> DATA = 111; pbnode P = findancestor (PT, n, n); If (P! = NULL) {cout <p-> data <Endl;} else {cout <"not found \ n";} return 0 ;}

Case 2: A binary tree is a common binary tree, but contains a pointer to the parent node.
Idea: since there is a pointer to the parent node, we can start from the two input nodes and get the path from the two to the root node, then the problem is converted to the first public node problem of two single-chain tables. code:
/* Binary tree common ancestor Series 2. the binary tree contains pointers to the parent node */# include <iostream> using namespace STD; typedef struct _ node _ {int data; struct _ node _ * left; struct _ node _ * right; struct _ node _ * parent;} node, * pnode, * ptree;/* find the lowest common ancestor */pnode findancestor (ptree PT, pnode pnode1, pnode pnode2) {If (Pt = NULL | pnode2 = NULL | pnode1 = NULL) {return NULL ;} if (Pt = pnode1 | Pt = pnode2) {return NULL;}/* 1. calculate the path length from the two nodes to the root node */INT len1 = 0, len2 = 0; PN Ode ptemp = pnode1; while (ptemp! = NULL) {ptemp = ptemp-> parent; len1 ++;} ptemp = pnode2; while (ptemp! = NULL) {ptemp = ptemp-> parent; len2 ++;}/* 2. next it is equivalent to finding the public node */int dif = len1-len2 of two single-chain tables; pnode plong = pnode1; pnode Pshort = pnode2; If (DIF <0) {plong = pnode2; pshort = pnode1; DIF = len2-len1;} while (DIF> 0) // fast pointer first DIF step {plong = plong-> parent; DIF --;} // two pointers go at the same time. The first encounter is the lowest public ancestor while (plong! = NULL & Pshort! = NULL & plong! = Pshort) {plong = plong-> parent; Pshort = Pshort-> parent;} return plong;}/* sequential traversal */void display (ptree pt) {If (Pt = NULL) {return;} cout <Pt-> data <""; if (Pt-> left) {display (Pt-> left);} If (Pt-> right) {display (Pt-> right );}} /* construct a binary tree */void create (ptree * PT, pnode pparent) {int data; CIN> data; If (Data =-1) {return ;} * PT = (pnode) malloc (sizeof (node); If (* PT = NULL) {exit (-1) ;}( * PT)-> DATA = data; (* PT)-> left = NULL; (* P T)-> right = NULL; (* PT)-> parent = pparent; Create (& (* PT)-> left, * PT); Create (& (* PT) -> right, * PT);} int main () {ptree Pt = NULL; Create (& PT, null); pnode P = findancestor (PT, Pt-> right, pt-> left-> right); If (P! = NULL) {cout <p-> data <Endl;} else {cout <"not found... "<Endl;} display (PT); Return 0 ;}

Case 3: The tree is a common binary tree with no pointer to the parent nodeIdea: first, the first step is to find a path from the two input nodes to the root node, and then the path is ready. We can use an array to store the path, and then traverse the path in the first order. For details, see the code. Code:
/* Common ancestor of two nodes in the tree 3. the tree is a common binary tree with no pointer to the parent node */# include <stdio. h> # include <stdlib. h> typedef struct _ node _ {int data; struct _ node _ * left; struct _ node _ * right;} node, * pnode, * ptree; /* search for a path from the root to Val in the PT binary tree. Path stores the path array, index indicates the subscript of the current array, and Len indicates the array length */bool getnodepath (ptree PT, int Val, int * path, int index, int * Len) {If (Pt = NULL) {* Len = 0; return false ;} path [Index] = Pt-> data; If (Pt-> DATA = Val) {* Len = index + 1; // Index Returns tr from 0 UE;} else {bool can; Can = getnodepath (Pt-> left, Val, path, index + 1, Len); If (! Can) {can = getnodepath (Pt-> right, Val, path, index + 1, Len);} return can ;}} /* find the lowest common ancestor according to two paths */INT findancestor (int * path1, int len1, int * path2, int len2) {If (path1 = NULL | path2 = NULL | len1 <= 0 | len2 <= 0) {return 0;} int minlen = (len1 <len2 )? Len1: len2; int I; for (I = 0; I <minlen; I ++) {If (path1 [I]! = Path2 [I]) // The previous node of the first different node is the lowest common ancestor {break;} return path1 [I-1];} /* Create a binary tree first */void create (ptree * PT) {int data; scanf ("% d", & data); If (Data = 0) {return;} * PT = (pnode) malloc (sizeof (node); If (* PT = NULL) {exit (-1);} (* PT) -> DATA = data; (* PT)-> left = NULL; (* PT)-> right = NULL; Create (& (* PT)-> left ); create (& (* PT)-> right);}/* First traverse */void display (ptree pt) {If (Pt = NULL) {return ;} printf ("% d", Pt-> data); If (Pt-> left) {di Splay (Pt-> left);} If (Pt-> right) {display (Pt-> right);}/* destroy binary tree */void destroy (ptree pt) {If (Pt = NULL) {return;} If (Pt-> left) {destroy (Pt-> left);} If (Pt-> right) {destroy (Pt-> right);} Free (PT); Pt = NULL;} int main () {int t; while (scanf ("% d ", & T )! = EOF) {int I; int M, N; int len1, len2; for (I = 0; I <t; I ++) {ptree Pt = NULL; create (& pt); scanf ("% d", & M, & N); int path1 [10000]; int path2 [10000]; getnodepath (PT, m, path1, 0, & len1); getnodepath (PT, N, path2, 0, & len2); int result = findancestor (path1, len1, path2, len2); If (result! = 0) {printf ("% d \ n", result);} else {printf ("My God \ n") ;}destroy (PT );}} return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.