Simple Java solution with recursive

  • 2
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null)
            return null;
        TreeNode left = lowestCommonAncestor(root.left, p, q),
                right = lowestCommonAncestor(root.right, p, q);
        if(root == q || root == p || (left != null && right != null))
            return root;
        else if(left != null)
            return left;
        else if(right != null)
            return right;
        return null;

Log in to reply

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