#include <iostream>
#include <vector>
using std::endl;
using std::vector;
using std::cin;
using std::cout;
struct treeNode
{
int value;
treeNode*left;
treeNode*right;
};
<strong><span style="font-size:18px;">bool isAncestor(treeNode*root,treeNode*p)
{
if(root==NULL)
return false;
if(root==p)
return true;
return isAncestor(root->left,p)||isAncestor(root->right,p);
}
treeNode* findCommonAncestor(treeNode* root,treeNode* p,treeNode *q)
{
if(root==NULL)
return NULL;
if(root==p||root==q)
return root;
bool is_p_left=isAncestor(root->left,p);//p在左子樹
bool is_q_left=isAncestor(root->left,q);//q在左子樹
if (is_p_left!=is_q_left)//p、q異側
return root;
return is_p_left?findCommonAncestor(root->left,p,q):findCommonAncestor(root->right,p,q);
}
treeNode *findAncestor(treeNode* root,treeNode*p, treeNode*q)
{
if(!isAncestor(root,p)&&!isAncestor(root,q))
return NULL;
return findCommonAncestor(root,p,q);
}</span></strong>
treeNode * treeInsert(treeNode* head,int n)
{
treeNode* newNode=new treeNode;
newNode->left=newNode->right=NULL;
newNode->value=n;
if (head==NULL)
{
return newNode;
}
treeNode *head1=head,*head2=NULL;
while (head1!=NULL)//先確定待插入的父親節點
{
head2=head1;
if(head1->value>n)
head1=head1->left;
else
head1=head1->right;
}
if(head2->value>n)
{
head2->left=newNode;
}
else
{
head2->right=newNode;
}
return head;
}
int getHeight(treeNode * root)
{
if(root==NULL)
return 0;
else
return (getHeight(root->left)>getHeight(root->right)?getHeight(root->left):getHeight(root->right))+1;
}
void ByLevel(treeNode * root,int level)
{
if(root==NULL||level<0)
return ;
if (level==0)
cout<<root->value<<" ";
else
{
ByLevel(root->left,level-1);
ByLevel(root->right,level-1);
}
}
int main()
{
treeNode *head=NULL;
head=treeInsert(head,20);
head=treeInsert(head,15);
head=treeInsert(head,25);
head=treeInsert(head,30);
head=treeInsert(head,10);
head=treeInsert(head,18);
head=treeInsert(head,22);
head=treeInsert(head,23);
head=treeInsert(head,21);
treeNode* s1=head->right->left->left;//
treeNode* s2=head->right->left->right;//30
int high=getHeight(head);
for(int i=0;i<high;i++)
{
cout<<"LEVEL:"<<i+1<<endl;
ByLevel(head,i);
cout<<endl;
cout<<"__________________"<<endl;
}
treeNode* s3=findAncestor(head,s1,s2);
if(s3)
{ cout<<s2->value<<" and "<<s1->value<<" 's common ancestor is ";
cout<<s3->value;
}
return 0;
}
/*
時間複雜度分析:O(n)
設有2*n個節點
左子樹n個
右子樹n個
則isAncestor 第一次要遍歷2*n
第二次2*n/2
第三次2*n/2/2
每次減半
因此累加爲O(n)
*/
二叉樹公共祖先節點的查找
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.