該題目不能用go語言寫,因此使用了C語言(C++忘的更多...)。Go語言寫多了,判斷語句也忘了加括號,語句末尾忘了加";",一條語句的statement也加了"{}"。用C語言寫幾行代碼也是好的,免得全忘光了。
使用Go語言答題的時(shí)候,可以使用官方提供的測試,過濾掉一些低級語法錯(cuò)誤,也可以非常方便的在Gogland里寫測試案例進(jìn)行test、debug代碼,比C語言智能多了。
通過編譯、test、debug發(fā)現(xiàn)問題最終解決問題,總比費(fèi)了半天腦子沒發(fā)現(xiàn)一個(gè)低級錯(cuò)誤,然后去看別人的代碼要好吧。
題目
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.
解題思路
剛開始看的時(shí)候有點(diǎn)懵逼,遍歷到要找的節(jié)點(diǎn)也不能找他父親??!所以還是得仔細(xì)審題,注意到給的是BST,不是普通的二叉樹,肯定要從BST入手啊,想到這里就簡單了(就想都是easy的題,肯定簡單...)。
因?yàn)槭荁ST,所以對于一個(gè)樹和兩個(gè)目標(biāo)節(jié)點(diǎn),有三種情況:
- 兩個(gè)目標(biāo)節(jié)點(diǎn)值都小于樹的根節(jié)點(diǎn)的值,這種情況下所求LCA肯定在樹的左子樹上;
- 兩個(gè)目標(biāo)節(jié)點(diǎn)值都大于樹的根節(jié)點(diǎn)的值,這種情況下所求LCA肯定在樹的右子樹上;
- 兩個(gè)目標(biāo)節(jié)點(diǎn)中要么有一個(gè)節(jié)點(diǎn)值和樹的根節(jié)點(diǎn)值相等,要么一個(gè)大于一個(gè)小于樹的根節(jié)點(diǎn)值,這些情況下LCA就是樹的根節(jié)點(diǎn)了。
代碼
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if (root->val < p->val && root->val < q->val) {
return lowestCommonAncestor(root->right, p, q);
} else if (root->val > p->val && root->val > q->val) {
return lowestCommonAncestor(root->left, p, q);
} else {
return root;
}
}