求二叉樹中兩個節點的最近公共祖先節點
阿新 • • 發佈:2019-01-25
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
typedef struct BTNode
{
char data;
BTNode *lchild;
BTNode *rchild;
}BTNode;
BTNode *LowestCommonAncestor(BTNode *root,BTNode *p,BTNode *q)
{
BTNode *l , *r ,*temp;
if(root==NULL)
{
return NULL;
}
if(root->lchild == p || root->lchild==q || root->rchild ==p || root->rchild ==q) //至少一個結點在根結點的左子樹或者右子樹,此時直接是root結點
{
return root;
}
else
{
l = LowestCommonAncestor(root->lchild , p , q);
r = LowestCommonAncestor(root->rchild , p, q);
if(l != NULL && r != NULL)
{
return root;
}
else
{
temp = ( l != NULL) ? l:r;
return temp;
}
}
}
int main()
{
return 0;
}
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
typedef struct BTNode
{
char data;
BTNode *lchild;
BTNode *rchild;
}BTNode;
BTNode *LowestCommonAncestor(BTNode *root,BTNode *p,BTNode *q)
{
BTNode *l , *r ,*temp;
if(root==NULL)
{
return NULL;
}
if(root->lchild == p || root->lchild==q || root->rchild ==p || root->rchild ==q) //至少一個結點在根結點的左子樹或者右子樹,此時直接是root結點
{
return root;
}
else
{
l = LowestCommonAncestor(root->lchild , p , q);
r = LowestCommonAncestor(root->rchild , p, q);
if(l != NULL && r != NULL)
{
return root;
}
else
{
temp = ( l != NULL) ? l:r;
return temp;
}
}
}
int main()
{
return 0;
}