[LeetCode]Lowest Common Ancestor of a Binary Tree

第一个是普通二叉树,第二个是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);
        }
    }
}

 

posted @ 2015-12-05 08:00  Weizheng_Love_Coding  阅读(123)  评论(0编辑  收藏  举报