LeetCode 257. Binary Tree Paths 递归过程保存信息
来源:互联网 发布:彩票遗漏数据价值 编辑:程序博客网 时间:2024/06/14 20:32
257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5All root-to-leaf paths are:
[“1->2->5”, “1->3”]
题意
给定一个二叉树,返回根节点到叶子结点间的路径
思路
- 重点在于递归的过程,如何保持信息。
- 关于递归过程的return,要注意返回到哪里,返回给谁。
- 同样分解为子问题
代码
class Solution {public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if(root == NULL) //当前结点为空,表示本身就是一颗空树,这个时候返回res,res内也没任何元素 { return res; } if(root->left == NULL && root->right == NULL) //当前结点是叶子结点,将当前结点的值存入vector<string>中,便于返回left,right { res.push_back(to_string(root->val)); return res; } vector<string> left = binaryTreePaths(root->left); //获取当前结点左子树的路径 //遍历一遍当前节点左子树存储的路径,转换为当前节点到左子树的路径 for(int i=0;i<left.size();i++) { res.push_back(to_string(root->val)+"->"+left[i]); } vector<string> right = binaryTreePaths(root->right); //获取当前结点右子树的路径 for(int i=0;i<right.size();i++) { res.push_back(to_string(root->val)+"->"+right[i]); } return res; }};
结果
阅读全文
0 0
- LeetCode 257. Binary Tree Paths 递归过程保存信息
- [leetcode] 257. Binary Tree Paths
- 257. Binary Tree Paths LeetCode
- 【LeetCode】257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- LeetCode *** 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- Leetcode 257. Binary Tree Paths
- LeetCode-257.Binary Tree Paths
- 【leetcode】257. Binary Tree Paths
- [Leetcode]257. Binary Tree Paths
- LeetCode - 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- [leetcode] 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- 257.[Leetcode]Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- Intellij IDEA2017入门教程
- bzoj 3207 花神的嘲讽计划Ⅰ
- 几种直播流媒体协议
- Android编译系统环境初始化过程分析
- ubuntu linux 批量删除文件
- LeetCode 257. Binary Tree Paths 递归过程保存信息
- 简单关于原型链学习总结
- Synchronized 很重要!
- leapmotion驱动安装
- 新手基础(二)Head First Java练习:public class Mix4
- 根据指定的学科, 取出点击量前三的
- 535. Encode and Decode TinyURL
- 【队列】之链式存储结构
- Nginx安装