257. Binary Tree Paths
来源:互联网 发布:爆伤和黄字算法 编辑:程序博客网 时间:2024/06/06 07:01
问题描述
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[“1->2->5”, “1->3”]
思路分析
这道题是利用深度优先算法,把每个叶子的路径记录下来。首先创建一个储存父辈值的数组paths。在前序中,存入所遇到的节点的值。当遇到叶子时,不需要存入自己的值,只需要取出paths的值,形成路径链,存入结果中。然后访问完当前叶子,返回上一层递归。父辈的值,在后序中pop出paths.
如立体。paths的值为{1},{1,2},{1,2,5},{1},{1,3},{1},{}
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> result={}; //存储每一个叶的路径 if(root==NULL) { return result; } DFS(root,result); return result; } vector<int> paths={}; //储存叶的父辈 void DFS(TreeNode* root, vector<string>& result) { if(root->left==NULL&&root->right==NULL) { //当遇到叶时,就把他的父辈取出,形成路径 string temp=""; for(int i=0;i<paths.size();i++) { temp=temp+to_string (paths[i]); temp+="->"; } temp=temp+to_string ((root->val)); //最后加上自己 result.push_back(temp); return; } paths.push_back(root->val); //把非叶的节点加到父辈paths数组 if(root->left!=NULL) { DFS(root->left,result); } if(root->right!=NULL) { DFS(root->right,result); } paths.pop_back(); //当穷尽一条路径,即找到叶后,把叶的父辈删掉 }};
阅读全文
0 0
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- ruby 的代码块
- 看唐僧如何玩转PMP
- IONIC 表单标签的使用
- 【Spring in action】基于Java配置SpringMVC中使用Spring及SpringMVC各种请求详解
- 浅谈区块链技术
- 257. Binary Tree Paths
- 传统加密技术——置换加密(Py2.7实现)
- tensorflow 模型的持久化
- 自己动手写一个简单的MVC框架(第二版)
- Springmvc+Mybatis整合及api接口编写demo
- 关于响应式布局
- new和数组
- vue之路——单页面管理系统
- mac查看sshkey