Find the minimum common parent node of the two nodes in the binary tree.

Source: Internet
Author: User

Algorithm Design: traverse the binary tree and put the parent nodes of the two nodes into two linked lists respectively. Then, compare them sequentially to find the last same node, which is the lowest common node.

 

C pseudo code implementation:

List * h, * h1, * h2; bool find1 = false, find2 = false; void postVisit (BTNode * root) {if (root! = Null) {add (root, h); // add the root node to the postVisit (root-> lchild) linked list with h as the header; if (root-> lchild! = NULL) delete (root-> lchild, h); // delete the right root child node postVisit (root-> lchild) from the h linked list; if (root-> rchild! = NULL) delete (root-> rchild, h); // delete the left-Child root node from the h linked list if (root-> value = v1) {copy (h, h1); // find the first required node and copy all the nodes in the h linked list to find1 = true;} else (root-> value = v1) In h1 )) {copy (h, h2); // find the second required node and copy all nodes in the h linked list to find2 = true;} if (find1 & find2) // two linked lists are formed and returned sequentially after exiting;} void findParentNode (BTNode * root) {postVisit (root); for (List * p1 = h1, * p2 = h2; p1-> next-> node! = P2-> next-> node & p1! = NULL & p2! = NULL; p1 = p1-> next, p2 = p2-> next); if (p1-> node! = P2-> node) // No public node is found at this time, and the target node printf ("not same parent"); else printf (p1-> node) may not be found ); // output the lowest public node}

 

 

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.