class Solution {
public:
//在哪分开,哪里就是公共祖先!
//中序遍历二叉树
TreeNode* ans;
int lowestCommonAncestor(TreeNode* root, int p, int q) {
// write code here
int Min = min(p,q);
int Max = max(p,q);
InOrder(root, Min, Max);
return ans->val;
}
void InOrder(TreeNode* root, int min, int max)
{
//左根右
if(min < root->val && max < root->val) //如果都小于根节点,就往左走
{
InOrder(root->left, min, max);
}
else if(min <= root->val && max >= root->val) //如果开始分叉就找到了想要的根节点!
{
ans = root;
}
else{
InOrder(root->right, min, max); //如果都大于根节点,就往右走
}
}
};
标签:val,min,int,max,二叉,JZ68,搜索,root,InOrder
From: https://www.cnblogs.com/H43724334/p/18146859