给定一颗二叉树和两个节点p和q,寻找它们的最近公共祖先?
说明这颗二叉树,不是一颗二叉搜索树。
节点typedef struct _node{
int val;
node * pleft;
node * pright;
}node;
/*
先在一颗子树中找个某个节点是否存在
例如:t这个颗子树下是否存在p这个节点
*/
bool find_node(node *t, node *p)
{
//如果这颗子树已遍历完,都不存在,或者传入的子树就为空
if (!t)
return false;
//找到这个节点
if (t == p)
return true;
//先在左子树中找,不存在,再到右子树中找
bool bfound = find_node(t->pleft, p);
if(bfound)
return true;
return find_node(t->right, p);
}
node * find_public_parant(node* t, node*p, node*q)
{
//如果传入的子树节点为空,那么直接返回空,不存在
if (!t )
return NULL;
//有可能,p,q其中一个就等于根节点
if (t == p || t == q)
return t;