problem
solution
- 比較
root
p
q
三個節點的值 - 如果
root->val
是其他兩個節點的值,則return root
- 如果
root->val
小於其他兩節點的值,則向root->right
搜尋 - 如果
root->val
大於其他兩節點的值,則向root->left
搜尋 - 剩餘狀況,則
return root
option 1 - recursive
1 | class Solution { |
if(root->val > p->val && root->val > q->val)
可改成if(root->val > max(p->val, q->val) )
- postorder
沒用到BST特性1
2
3
4
5
6
7
8
9
10
11
12
13class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return root;
if(root ==p || root==q) return root;
TreeNode *l = lowestCommonAncestor(root->left, p, q);
TreeNode *r = lowestCommonAncestor(root->right, p, q);
if( l && r) return root;
else if(!l) return r;
return l;
}
};option 2 - iterative
不斷更新root 節點
1 | class Solution { |
analysis
- time complexity
O(n)
n is node number of tree - space complexity
O(h)
h is height of tree