Thursday, January 5, 2017

Leetcode/各大家 -- 235. Lowest Common Ancestor of a Binary Search Tree (Recursion+Iteration)

235. Lowest Common Ancestor of a Binary Search Tree (Recursion+Iteration)
  • Difficulty: Easy
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.

Company: Amazon Microsoft Facebook Twitter
思路1: recursion, 3 cases: a.base is when root = null or p or q, b.root too less, recur right subtree, c reverse case b
思路2: iterative, find a point where root is one of p,q or the parent node: right>root>left
Complexity: O(h) time where h is height of tree. O(lgN), Space O(h)
关键字: LinkedList, Recursion, Iteration

解法1: recursion

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null||root==p||root==q)return root;
        if(root.val>p.val&&root.val>q.val){
            root = lowestCommonAncestor(root.left,p,q);//traverse to left
        }else if(root.val<p.val&&root.val<q.val){
            root = lowestCommonAncestor(root.right,p,q);//traverse to right
        }//else 1 in left, 1 in right->return root
        return root;
    }
}

解法2: Iterative
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        while(root!=null){
            if(root.val>p.val && root.val>q.val) 
                root=root.left;
            else if(root.val<p.val && root.val<q.val)
                root = root.right;
            else//root equals one of p or q or parent
                return root;
        }
        return null;
    }
}


No comments:

Post a Comment