235. Lowest Common Ancestor of a Binary Search Tree

BST

1.問題

  • 給一個BST, 找出兩個node的LCA

2.想法

  • 提問

    • 確認題意: 是否是BST?

  • function header, parameter

  • test input

  • 說明想法

    • 利用BST特性

      • 當root比兩個node都大時, 將root移動到左邊

      • 當root比兩個node都小時, 將root移動到右邊

      • 當root介於兩個node間時, 將root停止移動

  • 測試計算複雜度

3.程式碼

/**
 * 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) {
        if (!root) {
            return NULL;
        }
        
        if (root->val > p->val && root->val > q->val) {
            return lowestCommonAncestor(root->left, p, q);
        } else if (root->val < p->val && root->val < q->val) {
            return lowestCommonAncestor(root->right, p, q);
        } else {
            return root;
        }
    }
};

Last updated