码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Lowest Common Ancestor of a Binary Tree

时间:2015-12-05 08:26:38      阅读:148      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!