Leetcode Answers 235

接着刷,昨晚睡的好解了乏,今天就能多搞几道。继续是一道Easy题,找在BST上的LCA。

题目:
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).”

1
2
3
4
5
6
7
_______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.

思路:
LCA算是一类经典问题,放在BST上是最基本的题型了。首先,BST的特点就是left.val < root < right.val,这是确定的。那么就可以想到,对于任意的p 和 q,如果他们的val是在某一个node的两边,那么他们的LCA就是这个node。其次,如果root的val和p、 q中的任何一者相等,那么这个root也是他们的LCA。最后,如果p 和 q都在root的同一侧,那么root = root.left / root.right,继续观察。于是一个recursive的解法就呼之欲出了。

Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root.val == p.val || root.val == q.val || (p.val < root.val && q.val > root.val) || (p.val > root.val && q.val < root.val)) return root;
return (p.val < root.val && q.val < root.val) ? LowestCommonAncestor(root.left, p, q) : LowestCommonAncestor(root.right, p, q);
}
}

考察:这里因为是BST所以十分好搞,如果不是BST而只是Binary Tree(BT),甚至于说不是BT而是多枝树如Trie,那么怎么搞?看下一题就知道了。

以上。

17-04-25
@Sturbridge