Paste_Image.png
My code:
/**
* 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;
return findAncestor(root, p, q);
}
private TreeNode findAncestor(TreeNode root, TreeNode p, TreeNode q) {
if ((root.val >= p.val && root.val <= q.val) || (root.val <= p.val && root.val >= q.val))
return root;
if (root.val < p.val && root.val < q.val)
return findAncestor(root.right, p, q);
else if (root.val > p.val && root.val > q.val)
return findAncestor(root.left, p, q);
return null;
}
}
My test result:
Paste_Image.png
這道題目就比較簡單了。他和上面那道題的區別是什么。
如果p或者q == root,那么,他們的祖先一定是root。因為沒找到的那個,一定在他的左右子樹上。而在上道題目中并不一定。
相當于兩個點pq同時進入這棵樹。如果發現root的值正好大于等于其中一個然后小于等于另外一個,那么,他就一定是最小祖先。
否則,pq只能同時小于或者大于root.val,那么,再選擇下一步遍歷的方向。
很類似于pre-order,先判斷root結點
**
總結: pre-order tree
**
Anyway, Good luck, Richardo!
My code:
/**
* 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 || p == null || q == null) {
return null;
}
else if (p == q) {
return p;
}
TreeNode curr = root;
HashSet<TreeNode> tracker = new HashSet<TreeNode>();
while (curr != null) {
if (curr.val < p.val) {
tracker.add(curr);
curr = curr.right;
}
else if (curr.val > p.val) {
tracker.add(curr);
curr = curr.left;
}
else {
tracker.add(curr);
break;
}
}
curr = root;
TreeNode pre = null;
while (curr != null) {
if (!tracker.contains(curr)) {
return pre;
}
else if (curr.val < q.val) {
pre = curr;
curr = curr.right;
}
else if (curr.val > q.val) {
pre = curr;
curr = curr.left;
}
else {
return q;
}
}
return null;
}
}
我的做法代碼比較復雜。
然后看了 Discuss,發現有更加簡潔的做法。
both iteration and recursion
具體看
reference:
https://discuss.leetcode.com/topic/18381/my-java-solution
Anyway, Good luck, Richardo! -- 08/28/2016
/**
* 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) {
TreeNode curr = root;
while (curr != null) {
if (p.val <= curr.val && curr.val <= q.val) {
return curr;
}
else if (q.val <= curr.val && curr.val <= p.val) {
return curr;
}
else if (p.val < curr.val && q.val < curr.val) {
curr = curr.left;
}
else {
curr = curr.right;
}
}
return null;
}
}
空間復雜度是 O(1)
現在的狀態出奇的差。跟女朋友關系飄忽不定。
突然發現她,才是我力量的源泉。沒有了她,我完全沒有斗志了。
其實現在準備的也差不多了,過去真的就是各安天命。
整個浪費的時間并不多,也不可能因為浪費這點時間而改變結果。
把面經好好鞏固下,加油吧!
Anyway, Good luck, Richardo! -- 10/23/2016