#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) */
原文地址:http://blog.csdn.net/hero_zouzongling/article/details/45694069