题目描述
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has 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 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
解题思路
这道题目和Lowest Common Ancestor of a Binary Search Tree
类似,只不过现在条件变为一颗普通的二叉树,要求出最低公共祖先。
首先要先确定给的两个node是否都在tree里,如果都在tree里的话,就可以分成3种情况,第一种情况是两个节点是在公共祖先的左右两侧,第二种情况是