LeetCode 235. Lowest Common Ancestor of a Binary Search Tree

1 class Solution {
2 public:
3     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
4         if(root->val >= p->val && root->val <= q->val || root->val >= q->val && root->val <= p->val) return root;
5         if(root->val > p->val) return lowestCommonAncestor(root->left, p, q);
6         return lowestCommonAncestor(root->right, p, q);
7     }
8 };

 注意等号,因为root可能等于p或q。

posted @ 2016-02-24 16:17  co0oder  阅读(149)  评论(0编辑  收藏  举报