LeetCode
C++
Binary Search Tree
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
取兩個 node 的最小祖先。
因為是 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;
}
};
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing