题目要求:
输入二叉树中的两个结点,输出这两个及诶单在数中最低的共同父结点。
题目分析:
还有一种情况:如果输入的两个结点中有一个或两个结点不在二叉树中,则输出没有共同父结点;
因此,可以在程序中定义一个flag=0,找到一个点之后flag就加1,最后判断的时候,如果flag=2,则说明在二叉树中找到了输入的两个结点。
代码实现:
#include <iostream> #include <stack> using namespace std; typedef struct BinaryTree { struct BinaryTree *left,*right; int data; }BinaryTree; int flag = 0; void initTree(BinaryTree **p,BinaryTree **a,BinaryTree **b); BinaryTree *GetLowestParent(BinaryTree *root,BinaryTree *X,BinaryTree *Y); int main(void) { BinaryTree *root,*a,*b; initTree(&root,&a,&b); BinaryTree *parent = GetLowestParent(root,a,b); if(parent && flag==2) cout << "最低公共父结点的值为:" << parent->data << endl; else cout << "没有最低公共父结点!" << endl; a = new BinaryTree; flag = 0; parent = GetLowestParent(root,a,b); if(parent && flag==2) cout << "最低公共父结点的值为:" << parent->data << endl; else cout << "没有最低公共父结点!" << endl; return 0; } // 10 // / // 5 12 // / // 4 7 void initTree(BinaryTree **p,BinaryTree **a,BinaryTree **b) { *p = new BinaryTree; (*p)->data = 10; BinaryTree *tmpNode = new BinaryTree; tmpNode->data = 5; (*p)->left = tmpNode; tmpNode = new BinaryTree; *b = tmpNode; tmpNode->data = 12; (*p)->right = tmpNode; tmpNode->left = NULL; tmpNode->right = NULL; BinaryTree *currentNode = (*p)->left; tmpNode = new BinaryTree; *a = tmpNode; tmpNode->data = 4; currentNode->left = tmpNode; tmpNode->left = NULL; tmpNode->right = NULL; tmpNode = new BinaryTree; tmpNode->data = 7; currentNode->right = tmpNode; tmpNode->left = NULL; tmpNode->right = NULL; cout << "二叉树为:" <<endl; cout << " " << 10<<endl; cout << " " <<"/" << " "<< "\" <<endl; cout << " " << 5 << " " << 12 << endl; cout << " " <<"/" << " "<< "\" <<endl; cout << 4 << " " << 7 << endl; } BinaryTree *GetLowestParent(BinaryTree *root,BinaryTree *X,BinaryTree *Y) { if(root == NULL) return NULL; if(X==root || Y==root) { flag++; return root; } BinaryTree *left = GetLowestParent(root->left,X,Y); BinaryTree *right = GetLowestParent(root->right,X,Y); if(left==NULL && right==NULL) return NULL; else if(left==NULL) return right; else if(right==NULL) return left; else return root; }