还是简单实现了作者的算法,对于何海涛非常敬佩。实现过程中遇查找树中某一个值的结点的函数,通过一个队列来实现,建树过程中不小心输入失误,一开始以为是前面的算法错了, 后来调试发现,其实是输入的顺序错误。 // 二叉树两个结点的最低共同父结点.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<iostream> #include<queue> using namespace std; typedef struct TreeNode{ int m_nValue; TreeNode* m_pLeft; TreeNode* m_pRight; }TreeNode,*BiTree; void CreateBiTree(BiTree &T); void InitBiTree(BiTree &T); void PreOrderTraverse(BiTree T,void(*Visit)(int)); BiTree LastCommonParent(BiTree T,BiTree p,BiTree q); BiTree findThePoint(BiTree T,int n); void Test(BiTree T); bool HasNode(BiTree t,BiTree p); void Visit(int n); int _tmain(int argc, _TCHAR* argv[]) { BiTree T; InitBiTree(T); CreateBiTree(T); PreOrderTraverse(T,Visit); cout<<endl; Test(T); system("pause"); return 0; } void InitBiTree(BiTree &T) { T=NULL; } void CreateBiTree(BiTree &T) { int n; cin>>n; if(n==0) T=NULL; else { T=(TreeNode*)malloc(sizeof(TreeNode)); T->m_nValue=n; CreateBiTree(T->m_pLeft); CreateBiTree(T->m_pRight); } } void PreOrderTraverse(BiTree T,void(*Visit)(int)) { if(T!=NULL){ Visit(T->m_nValue); PreOrderTraverse(T->m_pLeft,Visit); PreOrderTraverse(T->m_pRight,Visit); } } void Visit(int n) { cout<<n<<" "; } bool HasNode(BiTree t,BiTree p) { if(t==p)return true; bool res=false; if(t->m_pLeft!=NULL) res=HasNode(t->m_pLeft,p); if(!res&&t->m_pRight!=NULL) res=HasNode(t->m_pRight,p); return res; } //find the last parent of p and q in a tree with head T BiTree LastCommonParent(BiTree T,BiTree p,BiTree q) { if(T==NULL||p==NULL||q==NULL) return NULL; //check the left side bool leftHasNode1=false; bool leftHasNode2=false; if(T->m_pLeft!=NULL){ leftHasNode1=HasNode(T->m_pLeft,p); leftHasNode2=HasNode(T->m_pLeft,q); } if(leftHasNode1&&leftHasNode2){ if(T->m_pLeft==p||T->m_pLeft==q) return T; return LastCommonParent(T->m_pLeft,p,q); } //check the right bool rightHasNode1=false; bool rightHasNode2=false; if(T->m_pRight!=NULL){ if(!leftHasNode1) rightHasNode1=HasNode(T->m_pRight,p); if(!leftHasNode2) rightHasNode2=HasNode(T->m_pRight,q); } if(rightHasNode1&&rightHasNode2){ if(T->m_pRight==p||T->m_pRight==q) return T; return LastCommonParent(T->m_pRight,p,q); } if((leftHasNode1&&rightHasNode2)||(leftHasNode2&&leftHasNode1)) return T; return NULL; } //find the point of n in a Tree BiTree findThePoint(BiTree T,int n) { queue<BiTree>q; BiTree p; if(T){ q.push(T); while(!q.empty()){ p=q.front(); q.pop(); if(p->m_nValue==n) return p; if(p->m_pLeft!=NULL) q.push(p->m_pLeft); if(p->m_pRight!=NULL) q.push(p->m_pRight); } } return NULL; } void Test(BiTree T) { int n1,n2; while(cin>>n1>>n2){ if(n1==-1&&n2==-1)break; BiTree p1,p2,res; p1=findThePoint(T,n1); p2=findThePoint(T,n2); res=LastCommonParent(T,p1,p2); cout<<"The Last Common Parent is: "<<res->m_nValue<<endl; } }