美文网首页
235. Lowest Common Ancestor of a

235. Lowest Common Ancestor of a

作者: hyhchaos | 来源:发表于2016-12-07 11:20 被阅读9次

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

      本文链接:https://www.haomeiwen.com/subject/wkudmttx.html