Lowest Common Ancestor of a Binary Search Tree

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)。

你可能感兴趣的:(Binary search)