基本上一樣,只是tree的定義變成了binary tree了這樣。一模一樣的寫法我就不貼了。
而,binary tree 就是左邊都會比右邊小,所以可以一次只走一邊,加速!
唉別人都好聰明 QQ
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if ((root->val > p->val) && (root->val> q->val))
return lowestCommonAncestor(root->left, p,q);
if ((root->val < p->val) && (root->val < q->val))
return lowestCommonAncestor(root->right, p,q);
return root;
}
沒有留言:
張貼留言