首页 > 其他 > 详细

[LeetCode]Lowest Common Ancestor of a Binary Tree

时间:2015-12-05 08:25:23      阅读:211      评论:0      收藏:0      [点我收藏+]

第一个是普通二叉树,第二个是bst

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;
        }
        if (left != null || right != null) {
            return left != null ? left : right;
        }
        return null;
    }
}

 

 

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

 

[LeetCode]Lowest Common Ancestor of a Binary Tree

原文:http://www.cnblogs.com/vision-love-programming/p/5020955.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!