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

Lowest Common Ancestor of a Binary Search Tree

时间:2015-07-11 16:18:22      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______
       /                  ___2__          ___8__
   /      \        /         0      _4       7       9
         /           3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

解题思路:

CC150里4.7,但是原题是任意二叉树,这里更为简单,被限定为二叉搜索树。

根据BST的性质,root.left.val < root.val < root.right.val,并且所有子树也都是BST。我们的思路就变成判断p和q到底是在root的哪边。

1. 如果都小于root.val,一定同时在左侧,root不是lca,递归搜索左子树。

2. 如果都大于root.val,递归搜索右子树。

3. 否则,分别在root两侧,root就是lca。

/**
 * 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) {
        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 left == null ? right : left;
        }
        return root;
    }
}

上面算法的时间复杂度是O(logn),等于树的高度。下面的算法可以用在任意二叉树,不一定是BST。

仅在root左右子树都分别找到p和q的情况下返回root,说明root是p和q的lca。否则找不到的返回null,找到的一侧返回p或者q。

/**
 * 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) {
        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 left == null ? right : left;
        }
        return root;
    }
}

上面的解法时间复杂度为O(n)。

Lowest Common Ancestor of a Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4638644.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!