1 题目描述
2 算法思路
思路:这题和上一题不同,上一题由于二叉搜索树的特性,因此更为简单,本题更为一般,因此必须遍历整个二叉树才行。
递归算法:
- 终止条件;
- 当超过叶子节点,返回null
- 当root等于q或者p,直接返回root
- 递归工作
- 递归左子树,返回值记为left
- 递归右子树,返回值记为right
- 返回值:
- 当left和right都为空,说明,root的左右子树中都不含p,q,返回null
- 当left和right都不为,说明p,q在两侧,返回root
- 当left为空,right不为空,说明右子树中含有p或q,返回right ,有下面两个情况
- p,q其中一个在右子树,此时right指向p
- p,q两个节点都在右子树中,right指向最近的公共祖先
- 当left不为空,right为空,同理
3 代码
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)
return null;
if(left == null)
return right;
if(right == null)
return left;
return root;
}
}
4 提交结果