Given a binary tree, find the lowest common ancestor (LCA) of the Given nodes in the tree.
According to the definition of the LCA in Wikipedia: "The lowest common ancestor is defined between," nodes V and W as the L Owest node in T, have both V and W as descendants (where we allow a node to be a descendant of itself). "
_______3______ / ___5__ ___1__ / \ / 6 _2 0 8 / 7 4
For example, the lowest common ancestor (LCA) of nodes and are 5
1
3
. Another example is LCA of nodes 5
4
5
and are, since a node can be a descendant of itself according to the L CA definition.
The problem with the smallest common parent node of the binary tree is the follow up of the smallest common parent node of the previous lowest Common Ancestor of a binary search tree two forks. Different from the previous problem is that the problem is a two-fork tree, not a binary search tree, so you can not use its unique properties, so we can only in the binary search tree to search p and Q, and then find the last same node from the path is the parent node, we can use the recursive return implementation, writing is very concise, the code as follows:
class Solution {public: TreeNode* lowestcommonancestor (treenode* root, treenode* p, treenode* q) { ifreturn root; *left = Lowestcommonancestor (root-> left, p, q); *right = Lowestcommonancestor (root-> right, p, q); if return root; return left? left:right; }};
[Leetcode] Lowest Common Ancestor of a binary tree of the smallest common parent node