class Solution {
public:
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
TreeNode *p=root,*pre=NULL;
while(p!=pre)
{
pre=p;
if(haveVal(p->left, o1)&&haveVal(p->left, o2))
p=p->left;
if(haveVal(p->right, o1)&&haveVal(p->right, o2))
p=p->right;
}
return p->val;
}
bool haveVal(TreeNode* root, int o) {
if(!root)
return false;
if(root->val==o||haveVal(root->left,o)||haveVal(root->right,o))
return true;
return false;
}
};使用递归,haveVal函数返回以root为根节点的树是否有o值的结点

京公网安备 11010502036488号