给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
采用递归算法,如下
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null || root==p || root==q)
return root;
TreeNode l=lowestCommonAncestor(root.left,p,q);
TreeNode r=lowestCommonAncestor(root.right,p,q);
if(l==null)
return r;
if(r==null)
return l;
return root;
}
}
示例:输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 6, q = 4
(蓝色箭头代表孩子,橙色代码返回数值 n代表空)