leetcode 257:Binary Tree Paths
来源:互联网 发布:大数据的弱点有哪些 编辑:程序博客网 时间:2024/05/16 08:12
问题描述:
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”]
思路:
这又是一道遍历二叉树的题目,谨记叶节点的定义,做出操作判断。
这次我给类Solution增加一个私有成员result用来记录字符串数组,因为我想增加一个能递归调用的函数,然后里面也能够保存root-to-leaf路径,所以只能通过增加成员来实现了。
思路是深度优先遍历,每读取一个节点,就将其数值接到传入的字符串str后面,然后将str作为参数传入到儿子节点的读取中去。一旦遇到叶子节点,就将str添加到result数组。
前面稍微处理一下root节点,后面的问题就可以递归完成。
代码:
class Solution {private: vector<string> result;public: vector<string> binaryTreePaths(TreeNode* root) { if (root == NULL) return result; string str = ""; stringstream ss; string transf; ss << root->val; ss >> transf; str = str + transf; if (root->left == NULL && root->right == NULL) { result.push_back(str); } if (root->left) readVal(root->left, str); if (root->right) readVal(root->right, str); return result; } void readVal(TreeNode *root, string str) { stringstream ss; string transf; ss << root->val; ss >> transf; str = str + "->" + transf; //deal with the leaf node if (root->left == NULL && root->right == NULL) { result.push_back(str); } if (root->left) readVal(root->left, str); if (root->right) readVal(root->right, str); }};
0 0
- 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
- leetcode-257-Binary Tree Paths
- LeetCode 257Binary Tree Paths
- LeetCode 257 Binary Tree Paths
- leetcode 257 Binary Tree Paths
- LeetCode-257:Binary Tree Paths
- Android studio ndk环境配置
- 数据机构的基本定义
- 自定义信息框 C# Wpf
- lintcode: Remove Nth Node From End of List
- leetcode-211-Add and Search Word - Data structure design
- leetcode 257:Binary Tree Paths
- Linux运维细讲之vim的基础使用
- struts2自定义拦截器笔记
- UICollectionView之控件瀑布流
- hibernate里的session.get()和session.load()区别以及Hibernate.initialize(Obj)用法
- BigInteger大整数类高精度
- Hibernate.initialize(Obj)用法
- UVA 1354(p197)----Mobile Computing
- C++ 内存分布,编译与运行阶段探索?(暂时不确定标题)