8ms beats 100% Java recursive solution


  • 0
    B
    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if (p.val > q.val)
                return lowestCommonAncestor(root, q, p);
            if (root == null)
                return null;
            if (root.val >= p.val && root.val <= q.val)
                return root;
            else if (root.val > q.val)
                return lowestCommonAncestor(root.left, p, q);
            else if (root.val < p.val)
                return lowestCommonAncestor(root.right, p, q);
            return null;
        }
    }
    

Log in to reply
 

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