How could this one beats all in speed (8ms)?


  • 0
    L

    It also check if the nodes exist or not. It should be slow.

    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if (p.val > q.val) {
                TreeNode t = p;
                p = q;
                q = t;
            }
            
            if (p.val <= root.val && q.val >= root.val) {
                if (hasNode(root, p) && hasNode(root, q))
                    return root;
                else return null;
            }
            else if (p.val > root.val) 
                return lowestCommonAncestor(root.right, p, q);
            else if (q.val <root.val)
                return lowestCommonAncestor(root.left, p, q);
                
            return null;
        }
        
        boolean hasNode(TreeNode root, TreeNode n){
            if (root == null) return false;
            if (root == n) return true;
            
            if (root.val > n.val) return hasNode(root.left, n);
            else return hasNode(root.right, n);
        }
    }
    

Log in to reply
 

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