【LeetCode】: 235. Lowest Common Ancestor of a Binary Search Tree

tags: LeetCode C++ Binary Search Tree

Description

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

取兩個 node 的最小祖先。

https://en.wikipedia.org/wiki/Lowest_common_ancestor

Solution

因為是 BST 所以可以比大小,判斷如果兩個 node 分在判斷 node 的兩側,則 LCA 就一定是該 node,若落在兩邊,則更新當前 node 到那一側繼續判斷。

如果有 node 等於當前 node 的話則回傳當前 node。

/** * 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) { while(root!=nullptr){ if(root->val == p->val || root->val == q->val) return root; if(root->val > p->val && root->val < q->val) return root; if(root->val < p->val && root->val > q->val) return root; if(root->val < p->val && root->val < q->val) root = root->right; if(root->val > p->val && root->val > q->val) root = root->left; } return root; } };

也可以利用 Recursion 的方式遞迴查找。

/** * 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->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right, p, q); if(root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left, p, q); return root; } };
Select a repo