LeetCode(257)Binary Tree Paths
来源:互联网 发布:php重打包apk 编辑:程序博客网 时间:2024/05/02 09:12
【题目】
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"]【解答】
最直接的方法就是 DFS
【答案】
/** * 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: void dfs(TreeNode* root,string temp,vector<string> &v) { string s; s=to_string(root->val); if (temp=="") { temp=s; } else temp=temp+"->"+s; if (root->left==NULL && root->right==NULL) { v.push_back(temp); } else { if (root->left) { dfs(root->left,temp,v); } if (root->right) dfs(root->right,temp,v); } } vector<string> binaryTreePaths(TreeNode* root) { vector<string> v; if (root==NULL) //空树 return v; string temp=""; dfs(root, temp, v); return v; }};
2 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-257-Binary Tree Paths
- LeetCode 257Binary Tree Paths
- LeetCode 257 Binary Tree Paths
- leetcode 257 Binary Tree Paths
- [漫画]程序员的日常生活 62
- java的Iterator
- OpenStack依旧大行其道,但能否等来属于自己的时代
- Cookie入门
- [漫画]程序员的日常生活 63
- LeetCode(257)Binary Tree Paths
- 开源控件MPAndroidChart的使用
- [漫画]程序员的日常生活 64
- Two Sum
- Android Studio系列教程一--下载与安装
- 依赖倒转原则
- Qt中隐藏滚动条重新实现鼠标滚轮事件wheelEvent
- [漫画]程序员的日常生活 66
- [漫画]程序员的日常生活 65