236.Lowest Common Ancestor of a BinaryTree

给定一个二叉树和所要查找的两个节点,找到两个节点的最近公共父亲节点(LCA)。比如,节点5和1的LCA是3,节点5和4的LCA是5。

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);//如果p在左子树,则会返回p,否则返回空
        TreeNode right = lowestCommonAncestor(root.right, p, q);//如果q在右子树,则会返回q,否则返回空
        if(left != null && right != null){
            return root;//如果左右都不为空,则root肯定是祖先节点
        }
        return left == null ? right : left;
    }
}

猜你喜欢

转载自www.cnblogs.com/MarkLeeBYR/p/10536085.html