题目
示例
思路
有三种情况:
1.p,q在root的左右子树中,比如示例1;
2.rootp,q在p的左子树或右子树中,如示例2;
3.rootq,p在q的左子树或右子树中。
递归:
终止条件:
- 遍历到叶节点,仍未匹配p,q,返回null
- rootp或rootq,返回root;
递归左子节点,返回值记为left
递归右子节点,返回值记为right
- 若left和right都为null,则返回null
- 若left==null&&right !=null,则有两种情况
- p,q均位于root的右子树,此时right为p,q最近公共祖先
- p(或q)位于root右子树,此时right==p(或q)
- 若right==null&&left!=null,同2
- 若left和right都不为null,则root为p,q最近公共祖先
具体代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
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){
return right;
}
if(right == null){
return left;
}
return root;
}
}
时间复杂度:O(N),N为二叉树节点数,每个节点遍历一次。
空间复杂度:O(N),递归调用的栈深度为二叉树深度,二叉树最坏情况为一条链,此时深度为N。
参考资料