235. Lowest Common Ancestor of a Binary Search Tree

 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

// still dont know why the constuct is paritally defined ???

// idea :  case 1 : if root is between node a and node b, then root is the lca of a and b
// if root is bigger than both a and b, then we call recurisve on root.left
// if root is smaller than both a and b, then we call recurisve on root.right
// if root is equal to one of them, then root is the lca of a and b , same as case 1 
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
      
      
      // recursion + induction rules
      if(root.val > p.val && root.val > q.val){
        return lowestCommonAncestor(root.left, p, q);
      }
      if(root.val < p.val && root.val < q.val){
        return lowestCommonAncestor(root.right, p, q);
      }
      return root;
        
    }
}

 带返回值的 recursion

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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given binary search tree:  root = [6,2,8,0,4,7,9,null,null,3,5]

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

 

idea: lca(3, 4) is 4 , because both 3 and 4 are smaller than root 6, so move root to the left  , which is 2, both 3 and 4 are bigger than 2, so move root to the right

which is 4 , since we found a number 4 , that is the same as one of 3 and 4 , we know its the lca of 3 and 4 

 

another case, lca(3, 5) = 4

since both 3 and 5 are smaller than 6, so move root to the left, now we are at 2, since both 3 and 5 are bigger than 2, so we move root to the right, we

are 4 now, since 4 is in between 3 and 5, we know the lca is 4 

 

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself 
             according to the LCA definition.

posted on 2018-08-09 17:34  猪猪&#128055;  阅读(93)  评论(0)    收藏  举报

导航