1. 程式人生 > >LC.235.Lowest Common Ancestor of a Binary Search Tree

LC.235.Lowest Common Ancestor of a Binary Search Tree

否則 where 最小 script sel init 等於 返回 sin

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
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.

像這種返回一個node 的東西,結果要不就從左邊來, 要不就從右邊來,否則就是null
凡事遍歷的點,先查一下自己滿足不滿足,不滿足的話,稍微pruning 一下,大膽往左右兩邊丟,然後等答案返回來
check bal. tree height, path sum i 都是這樣

 1 // the goal is to find the root that would sit in the middle
 2     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
 3         //base case
4 if (root == null) return null ; 5 int min = Math.min(p.val, q.val) ; 6 int max = Math.max(p.val, q.val) ; 7 //pre order:看看當前點是不是滿足的值 8 if (root.val>=min && root.val <= max) return root ; 9 //the left: branch pruning > max, then go left: 左邊返回就一層層往上返回 10 if (root.val > max){ 11 return lowestCommonAncestor(root.left, p, q) ; 12 } 13 //the right: branch pruning: <min: then go right: 右邊返回就一層層往上返回 14 if (root.val < min){ 15 return lowestCommonAncestor(root.right, p, q) ; 16 } 17 //不從左邊,也不從右邊的話,就是NULL 18 return null; 19 }

這道題首先要明確題目背景---二叉搜索樹。也正是因為是二叉搜索樹,所以我們可以利用二叉搜索樹從小到大排好序的特性來做。

對於一個root和另外兩個Node來說,它們的值會有以下幾種情況:

1. root.val < p.val && root.val < q.val 此時,兩個node的值都比root大,說明這兩個值在root右邊的subtree裏,且他們的最小公共頂點不可能是當前root

2. root.val > p.val && root.val > q.val 此時,兩個node的值都比root小,說明這兩個值在root左邊的subtree裏,且他們的最小公共頂點不可能是當前root

3. else,此時 root的值在p,q之間(或等於p,q中的某一個),此時,當前root即為公共頂點



LC.235.Lowest Common Ancestor of a Binary Search Tree