Microsoft interview questions: find the nearest common parent node of any two nodes on the binary tree.

Source: Internet
Author: User

 

Find the nearest common parent node of any two nodes on the binary tree.

 

 

 

It is required that the nearest common parent node (LCA, lowest common ancestor) of the two nodes can be traversed in descending order of the tree. If the two nodes are not on the same line, they must be on the left and right trees of node A respectively, node A is required to traverse to the first node that meets this condition in the descending order. In addition, when the two nodes are online, the requested node A is the parent node of the two nodes with the lowest levels.

Static bool lca (Node * root, int va, int vb, Node * & result, Node * parrent) <br/>{< br/> // left/right: whether the left/right subtree contains one of the two vertices to be judged <br/> bool left = false, right = false; <br/> if (! Result & root-> left) left = lca (root-> left, va, vb, result, root); <br/> if (! Result & root-> right) right = lca (root-> right, va, vb, result, root ); <br/> // whether the current node is one of the two vertices to be judged <br/> bool mid = false; <br/> if (root-> data = va | root-> data = vb) mid = true; <br/> if (! Result & int (left + right + mid) = 2) {<br/> if (mid) result = parrent; <br/> else result = root; <br/>}< br/> return left | mid | right; <br/>}</p> <p> Node * lca (Node * root, int va, int vb) <br/>{< br/> if (root = NULL) return NULL; <br/> Node * result = NULL; <br/> lca (root, va, vb, result, NULL); <br/> return result; <br/>}< br/>

 

 

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.