二叉树两个结点的最低公共父结点 【微软面试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; 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; }
很多时候不是我们做不好,而是没有竭尽全力......
分类:
【微软面试100题】
posted on 2014-11-23 13:39 tractorman 阅读(192) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?