题目:
分析:
总感觉搜索树有一定的特征,
忍住没看答案,终于想出来了,
直接从根开始比较左右即可。
代码:
/**
* 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) {
int m1=max(p->val,q->val);
int m2=min(p->val,q->val);
while(1)
{
if(root->val==m1||root->val==m2) return root;
if(root->val<m2) root=root->right;
else if(root->val>m1) root=root->left;
else return root;
}
}
};