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.