Java Solution: Comparing the root to p and q at each iteration


  • 0
    C
    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;
    }

  • 0
    S

    it doesn't work when one of the node is not found


  • 0

    Won't it exceed time limit?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.