235. Lowest Common Ancestor of a Binary Search Tree

	public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        while (root != null) {
            if 		((root.val - p.val) > 0 && (root.val - q.val) > 0) root = root.left;
            else if ((root.val - p.val) < 0 && (root.val - q.val) < 0) root = root.right;
            else 													   break;
        }
        return root;
    }
   
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root.val == p.val || root.val == q.val) return root;
    
        if (p.val < root.val && root.val < q.val) return root;
        if (q.val < root.val && root.val < p.val) return root;
        
        if (p.val < root.val) 
            return lowestCommonAncestor(root.left, p, q);
        
        if (p.val > root.val) 
            return lowestCommonAncestor(root.right, p, q);
        return null;
    }

你可能感兴趣的:(leetcode)