Any Java solution less than 10ms? Mine is 10ms and based on recursion.


  • 0
    public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        int mid=root.val;
        int pv=p.val;
        int qv=q.val;
        TreeNode min=pv<qv?p:q;
        TreeNode max=pv>qv?p:q;
        if(min.val<=mid&&max.val>=mid)
            return root;
        if(max.val<mid)
            return lowestCommonAncestor(root.left,p,q);
        else if(min.val>mid)
                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.