235. Lowest Common Ancestor of a Binary Search Tree (E)

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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1:

<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 13px; margin-top: 0px; margin-bottom: 1em; overflow: auto; background: var(--dark-bg); border-color: rgb(51, 51, 51); color: var(--font) !important; padding: 10px 15px; line-height: 1.6; border-radius: 3px; white-space: pre-wrap; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.
</pre>

Example 2:

image

<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 13px; margin-top: 0px; margin-bottom: 1em; overflow: auto; background: var(--dark-bg); border-color: rgb(51, 51, 51); color: var(--font) !important; padding: 10px 15px; line-height: 1.6; border-radius: 3px; white-space: pre-wrap; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
</pre>

Example 3:

<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 13px; margin-top: 0px; margin-bottom: 1em; overflow: auto; background: var(--dark-bg); border-color: rgb(51, 51, 51); color: var(--font) !important; padding: 10px 15px; line-height: 1.6; border-radius: 3px; white-space: pre-wrap; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">Input: root = [2,1], p = 2, q = 1
Output: 2
</pre>

Constraints:

  • The number of nodes in the tree is in the range [2, 10<sup>5</sup>].
  • -10<sup>9</sup> <= Node.val <= 10<sup>9</sup>
  • All Node.val are unique.
  • p != q
  • p and q will exist in the BST.

我的答案:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        vector<TreeNode*> ancester1, ancester2;
        
        SearchNode(root, p, ancester1);
        SearchNode(root, q, ancester2);
        
        // cout << ancester1[0]->val << " - " << ancester2[0]->val << endl;
        int i = 1;
        for (; i<ancester1.size() and i<ancester2.size(); ++i) {
            // cout << ancester1[i]->val << " - " << ancester2[i]->val << endl;
            if (ancester1[i] != ancester2[i]) {
                return ancester1[i-1];
            }
        }
        return ancester1[i-1]; // mark2
    }
    void SearchNode(TreeNode* root, TreeNode* node, vector<TreeNode*>& ancester) {
        if (node->val == root->val) {
            ancester.push_back(root); // mark1
            return;
        }
        ancester.push_back(root);
        if (node->val < root->val) {
            SearchNode(root->left, node, ancester);
        }
        else {
            SearchNode(root->right, node, ancester);
        }
    }
};

Runtime: 28 ms, faster than 90.94% of C++ online submissions for Lowest Common Ancestor of a Binary Search Tree.
Memory Usage: 24 MB, less than 24.08% of C++ online submissions for Lowest Common Ancestor of a Binary Search Tree.

感覺(jué)這么做下來(lái),不是E的題潜腻。

  • 首先需要想到是binary search tree衰猛,所以存儲(chǔ)每個(gè)node的ancestor比較容易了溃肪,正向搜索也只有唯一解
  • 其次一個(gè)坑是mark1处嫌,需要把自己也放到ancestor里面
  • 最后mark2的地方也需要注意糟描,到這一步說(shuō)明前面的ancestor匹配都對(duì)吨掌,只是size不同出來(lái)斩个,所以就需要return ancester1[i-1];胯杭,但注意不是return ancester1[i];,因?yàn)槌鰜?lái)的i已經(jīng)++過(guò)了

不過(guò)結(jié)合binary search tree的性質(zhì)萨驶,其實(shí)有更簡(jiǎn)單的方法
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/solution/
官方答案

默寫(xiě)recursive答案:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* ans = root;
        if (ans->val > p->val and ans->val > q->val) {
            ans = lowestCommonAncestor(root->left, p, q);
        }
        else if (ans->val < p->val and ans->val < q->val) {
            ans = lowestCommonAncestor(root->right, p, q);
        }
//         else {
            
//         }
        return ans;
    }
};

Runtime: 36 ms, faster than 38.67% of C++ online submissions for Lowest Common Ancestor of a Binary Search Tree.
Memory Usage: 23.9 MB, less than 24.08% of C++ online submissions for Lowest Common Ancestor of a Binary Search Tree.

默寫(xiě)iterative答案:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* ans = root;
        while (ans != p and ans != q) {
            if (ans->val > p->val and ans->val > q->val) {
                ans = ans->left;
            }
            else if (ans->val < p->val and ans->val < q->val) {
                ans = ans->right;
            }
            else {
                break;
            }
        }
        
        return ans;
    }
};

Runtime: 24 ms, faster than 98.52% of C++ online submissions for Lowest Common Ancestor of a Binary Search Tree.
Memory Usage: 23.9 MB, less than 24.08% of C++ online submissions for Lowest Common Ancestor of a Binary Search Tree.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末歉摧,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子腔呜,更是在濱河造成了極大的恐慌叁温,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,607評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件核畴,死亡現(xiàn)場(chǎng)離奇詭異膝但,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)谤草,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)跟束,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人丑孩,你說(shuō)我怎么就攤上這事冀宴。” “怎么了温学?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,960評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵略贮,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng)逃延,這世上最難降的妖魔是什么览妖? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,750評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮揽祥,結(jié)果婚禮上讽膏,老公的妹妹穿的比我還像新娘。我一直安慰自己拄丰,他們只是感情好府树,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著愈案,像睡著了一般挺尾。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上站绪,一...
    開(kāi)封第一講書(shū)人閱讀 51,604評(píng)論 1 305
  • 那天遭铺,我揣著相機(jī)與錄音,去河邊找鬼恢准。 笑死魂挂,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的馁筐。 我是一名探鬼主播涂召,決...
    沈念sama閱讀 40,347評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼敏沉!你這毒婦竟也來(lái)了果正?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,253評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤盟迟,失蹤者是張志新(化名)和其女友劉穎秋泳,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體攒菠,經(jīng)...
    沈念sama閱讀 45,702評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡迫皱,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了辖众。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片卓起。...
    茶點(diǎn)故事閱讀 40,015評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖凹炸,靈堂內(nèi)的尸體忽然破棺而出戏阅,到底是詐尸還是另有隱情,我是刑警寧澤啤它,帶...
    沈念sama閱讀 35,734評(píng)論 5 346
  • 正文 年R本政府宣布饲握,位于F島的核電站私杜,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏救欧。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評(píng)論 3 330
  • 文/蒙蒙 一锣光、第九天 我趴在偏房一處隱蔽的房頂上張望笆怠。 院中可真熱鬧,春花似錦誊爹、人聲如沸蹬刷。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,934評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)办成。三九已至,卻和暖如春搂漠,著一層夾襖步出監(jiān)牢的瞬間迂卢,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,052評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工桐汤, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留而克,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,216評(píng)論 3 371
  • 正文 我出身青樓怔毛,卻偏偏與公主長(zhǎng)得像员萍,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子拣度,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容