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.
解题思路
- Divide & Conquer 的思路
- 如果
root
为空,则返回空 - 如果
root
等于其中某个node
,则返回root
- 如果上述两种情况都不满足,则divide,左右子树分别调用该方法
- Divide & Conquer中治这一步要考虑清楚,本题三种情况
- 如果
left
和right
都有结果返回,说明root是最小公共祖先 - 如果只有
left
有返回值,说明left
的返回值是最小公共祖先 - 如果只有?
right
有返回值,说明?right
的返回值是最小公共祖先
1 class Solution { 2 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 3 if(root ==null || p==root||q==root) return root; 4 TreeNode lp = lowestCommonAncestor(root.left,p,q); 5 TreeNode rp = lowestCommonAncestor(root.right,p,q); 6 if(lp!=null&&rp!=null) return root; 7 if(lp==null&&rp!=null) return rp; 8 if(lp!=null&&rp==null) return lp; 9 return null; 10 } 11 }