思路:
注意本题是求二叉树的,而不是二叉搜索树的,区别是:
二叉搜索树不需要判断null返回,而二叉树需要
代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null||p==root||q==root){
return root;
}
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);
//如果left为空,则p、q一定在右侧
if(left==null) return right;
if(right==null) return left;
return root;
}
}
分解:
1)注意本题是求二叉树的,而不是二叉搜索树的,区别是:
二叉搜索树根节点的左边都小于根节点,根节点的右边都大于根节点。而二叉树是随机的,如:
复杂度分析:
时间复杂度:O(N)最差遍历N个节点
空间复杂度:O(N)递归深度最差为N