[LeetCode By Go 81]235. Lowest Common Ancestor of a Binary Search Tree

該題目不能用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),有三種情況:

  1. 兩個(gè)目標(biāo)節(jié)點(diǎn)值都小于樹的根節(jié)點(diǎn)的值,這種情況下所求LCA肯定在樹的左子樹上;
  2. 兩個(gè)目標(biāo)節(jié)點(diǎn)值都大于樹的根節(jié)點(diǎn)的值,這種情況下所求LCA肯定在樹的右子樹上;
  3. 兩個(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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容