Interview question: find the nearest common parent node of any two nodes on the binary tree.

Source: Internet
Author: User
In fact, we can use the back-order traversal of the tree. When you access the requested node A, 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, special processing must be performed on the two nodes online.

Code :
Static Bool LCA (node * Root, Int Va, Int VB, node *& Result, node * Parrent)
{
// Whether left/right subtree contains one of the two vertices to be judged
Bool Left = False , Right = False ;
If ( ! Result && Root -> Left) left = LCA (Root -> Left, VA, VB, result, root );
If ( ! Result && Root -> Right) Right = LCA (Root -> Right, VA, VB, result, root );
// Whether the current mid node is one of the two vertices to be judged
Bool Mid = False ;
If (Root -> Data = VA | Root -> Data = VB) Mid = True ;
If ( ! Result && Int (Left + Right + Mid) = 2 ) {
If(MID) Result=Parrent;
ElseResult=Root;
}
Return Left | Mid | Right;
}

Node * LCA (node * Root, Int Va, Int VB)
{
If(Root=Null)ReturnNULL;
Node*Result=NULL;
LCA (root, VA, VB, result, null );
ReturnResult;
}

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.