寻找最低共同父节点(LCA)
代码如下:
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q)
return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null){ //one in left, one in right
return root;
}else if (left != null && right == null){ //both in the left
return left;
}else if (left == null && right != null){ //both in the right
return right;
}else
return null;
}
}
解释:
lowestCommonAncestor用来检查某个subtree是否包含p和q其中的至少1个