235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree_第1张图片

Java,答案的想法很好,利用了二分树的特性

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
     while ((root.val - p.val) * (root.val - q.val) > 0)
        root = q.val < root.val ? root.left : root.right;
        return root;   
    }
}

你可能感兴趣的:(235. Lowest Common Ancestor of a Binary Search Tree)