Minimum common parent node of binary tree for interview training

Source: Internet
Author: User

Question: The Node definition of a binary tree is as follows:

Struct treenode

{

Int m_nvalue;

Treenode * m_pleft;

Treenode * m_pright;

};

Input two nodes in the binary tree and output the lowest common parent node among the two nodes.

My idea is to recursively traverse a binary tree, but when a node value is the same, if it is the left subtree, it will traverse the right subtree (of course another function processing at this time ), and vice versa.

The idea on the internet is quite good.

After traversing in the descending order, first determine whether the left subtree contains a node, then determine whether the right subtree contains, and finally determine whether the current node contains.

As long as two of the three nodes meet the minimum public parent node, because it is post-sequential traversal.

  1. Static bool LCA (node * root, int va, int VB, node * & result, node * parrent)
  2. {
  3. // Left/right: whether the left/right subtree contains one of the two vertices to be judged
  4. Bool left = false, Right = false;
  5. If (! Result & root-> left) Left = LCA (root-> left, VA, VB, result, root );
  6. If (! Result & root-> right) Right = LCA (root-> right, VA, VB, result, root );
  7. // Whether the current mid node is one of the two vertices to be judged
  8. Bool mid = false;
  9. If (root-> DATA = va | root-> DATA = VB) Mid = true;
  10. If (! Result & int (left + right + mid) = 2 ){
  11. If (MID) Result = parrent;
  12. Else result = root;
  13. }
  14. Return left | mid | right;
  15. }
  16. Node * LCA (node * root, int va, int VB)
  17. {
  18. If (root = NULL) return NULL;
  19. Node * result = NULL;
  20. LCA (root, VA, VB, result, null );
  21. Return result;
  22. }

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.