The lowest common ancestor node in a binary tree

Source: Internet
Author: User

Problem: Given two nodes in a binary tree, findLowestFor example, node 6 and node 9 have the lowest public ancestor node of node 5.


This problem seems to be related to the issue of public substrings. If we can find the paths from two nodes to the root node, we can use the matching algorithm to obtain the public path, the last node in this path is the lowest common ancestor node.

The Haffman code enlightened me. I plan to use 0 to show the left direction, and 1 to show the right direction. For example, "101" indicates that the node is from the root node. Go to the right Child A, then to the left child B of "A", and then to the right Child C of "B. Therefore, the path from the root node to node C can be represented by an integer of 101, that is, 5. Based on this idea, we only need to use an integer to represent the path from the root node to any node (if the path is greater than 32, we can consider using a large integer or simulating a large integer ).


Having thought of this layer, there is no difficulty. We only need to find the root node for the two nodes respectively (if the question requires starting from the root node) to the two node paths, find the last node in the public path.

Source code.


Source:

He Haitao blog: http://zhedahht.blog.163.com/blog/static/25411174201081263815813/

The author mentioned two solutions in this article. One is recursive. If both nodes are in the left or right subtree of the current node, their lowest common ancestor nodes must be in the left or right subtree. If they are scattered in two Subtrees, the current node is the lowest common ancestor node.

Another solution is similar to the solution in this article, except that the space complexity is higher than the solution in this article.

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.