二叉树两个结点的最低公共父结点 【微软面试100题 第七十五题】
生活随笔
收集整理的這篇文章主要介紹了
二叉树两个结点的最低公共父结点 【微软面试100题 第七十五题】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目要求:
輸入二叉樹中的兩個結點,輸出這兩個及誒單在數中最低的共同父結點。
題目分析:
還有一種情況:如果輸入的兩個結點中有一個或兩個結點不在二叉樹中,則輸出沒有共同父結點;
因此,可以在程序中定義一個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;elsecout << "沒有最低公共父結點!" << endl;a = new BinaryTree;flag = 0;parent = GetLowestParent(root,a,b);if(parent && flag==2)cout << "最低公共父結點的值為:" << parent->data << endl;elsecout << "沒有最低公共父結點!" << 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;elsereturn root; }
?
轉載于:https://www.cnblogs.com/tractorman/p/4116437.html
總結
以上是生活随笔為你收集整理的二叉树两个结点的最低公共父结点 【微软面试100题 第七十五题】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【JUC】JDK1.8源码分析之Conc
- 下一篇: mongo数据库CRUD