235. Lowest Common Ancestor of a Binary Search Tree

# Easy, DFS

Key: 等同于找到这两个点的第一个分叉处。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        int pval = p.val, qval = q.val;
                
        if(root.val > Math.max(pval, qval)) 
            return lowestCommonAncestor(root.left, p, q);
        
        if(root.val < Math.min(pval, qval))
            return lowestCommonAncestor(root.right, p, q);
        
        return root;
    }
}

Last updated

Was this helpful?