这道题和上一道求解最低公共祖先的不同在于是一般的二叉树,只能遍历节点来获取信息
- 通过返回节点是否为空判定子树中是否有pq节点
- 三种情况
- p和q分别在两颗子树中:那么当前节点就是最低公共祖先
- p和q都在左子树:将问题转换为在当前节点的左子树找p和q的最低公共祖先
- p和q都在右子树:将问题转换为在当前节点的右子树找p和q的最低公共祖先
package tree.No236;
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 && right != null)
return root;
return (left == null ? right : left);
}
}