在二元树中找出何为某一值的所有路径 【微软面试100题 第四题】
题目要求:
输入一个整数和一颗二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如输入22,和二叉树如下
10
/ \
5 12
/ \
4 7
则打印出两条路径:10-->12和10-->5-->7.
参考资料:剑指offer第25题
题目分析:
采用变量expectedSum,currentSum,path。expectedSum表示输入的整数,path为队列,表示之前经过的路径,currentSum表示之前经过路径各结点元素的和。
如果加上当前结点,expectedSum=currentSum,且当前结点为根结点,则打印路径path;如果不满足则继续递归遍历。
每次进入一个结点,path队列入队该元素,当递归处理了当前结点的子结点之后,最后需要把当前结点出队列。这样才能保证遍历某条路径时保存到path中的值,不会影响其他路径。

#include <iostream> #include <queue> using namespace std; typedef struct BinaryTreeNode { BinaryTreeNode *left,*right; int data; }BinaryTreeNode; void findPath(BinaryTreeNode *pRoot,int expectedSum); void initTree(BinaryTreeNode **p); int main(void) { BinaryTreeNode *pRoot = NULL; initTree(&pRoot); findPath(pRoot,22); return 0; } void findPath(BinaryTreeNode *pRoot,int expectedSum,deque<int> &path,int currentSum); void findPath(BinaryTreeNode *pRoot,int expectedSum) { if(pRoot == NULL) return ; deque<int> path; int currentSum = 0; findPath(pRoot,expectedSum,path,currentSum); } //--------------------核心代码---------------------------------- void findPath(BinaryTreeNode *pRoot,int expectedSum,deque<int> &path,int currentSum) { currentSum += pRoot->data; path.push_back(pRoot->data); bool isLeaf = pRoot->left==NULL && pRoot->right==NULL; if(isLeaf && currentSum==expectedSum) { cout << "A path is found:"; deque<int>::iterator iter = path.begin(); for(;iter != path.end();iter++) { cout << *iter; if(iter+1 != path.end()) cout << "-->"; } cout << endl; } if(pRoot->left != NULL) findPath(pRoot->left,expectedSum,path,currentSum); if(pRoot->right != NULL) findPath(pRoot->right,expectedSum,path,currentSum); path.pop_back(); } // 10 // / \ // 5 12 // / \ // 4 7 void initTree(BinaryTreeNode **p) { *p = new BinaryTreeNode; (*p)->data = 10; BinaryTreeNode *tmpNode = new BinaryTreeNode; tmpNode->data = 5; (*p)->left = tmpNode; tmpNode = new BinaryTreeNode; tmpNode->data = 12; (*p)->right = tmpNode; tmpNode->left = NULL; tmpNode->right = NULL; BinaryTreeNode *currentNode = (*p)->left; tmpNode = new BinaryTreeNode; tmpNode->data = 4; currentNode->left = tmpNode; tmpNode->left = NULL; tmpNode->right = NULL; tmpNode = new BinaryTreeNode; tmpNode->data = 7; currentNode->right = tmpNode; tmpNode->left = NULL; tmpNode->right = NULL; }
很多时候不是我们做不好,而是没有竭尽全力......
分类:
【微软面试100题】
posted on 2014-10-26 22:23 tractorman 阅读(244) 评论(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如何颠覆传统软件测试?测试工程师会被淘汰吗?