Add to List 257. Binary Tree Paths
来源:互联网 发布:python取消注释快捷键 编辑:程序博客网 时间:2024/06/06 00:59
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”]
这道题是利用DFS算法的思路。先从root出发,然后递归左子树,再递归右子树。注意这里to_string函数用于将int型转化为string型
代码如下:
/** * 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>v; vector<string> binaryTreePaths(TreeNode* root) { if(!root)return v; helper(root,to_string(root->val)); return v; } void helper(TreeNode* root,string t){ if(!root->left&&!root->right){ v.push_back(t); return; } if(root->left){ helper(root->left,t+"->"+to_string(root->left->val)); } if(root->right){ helper(root->right,t+"->"+to_string(root->right->val)); } }};
阅读全文
0 0
- Add to List 257. Binary Tree Paths
- Medium: Binary Tree Paths Add to List
- Add to List 563. Binary Tree Tilt
- leetcode104~Maximum Depth of Binary Tree Add to List
- 104.Maximum Depth of Binary Tree Add to List
- leetcode124~Binary Tree Maximum Path Sum Add to List
- LeetCode98. Validate Binary Search Tree Add to List
- 104. Maximum Depth of Binary Tree Add to List DescriptionHintsSubmissions
- LeetCode 98. Validate Binary Search Tree Add to List
- LeetCode 99. Recover Binary Search Tree Add to List
- Add to List 111. Minimum Depth of Binary Tree
- 【LeetCode】Add to List 606. Construct String from Binary Tree
- leetcode- Add to List 669. Trim a Binary Search Tree
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 公约数和公倍数
- Android入门之RecyclerView
- HRBUST 1214取方格(DP)
- NumPy-快速处理数据
- Ajax的使用以及跨域(上)
- Add to List 257. Binary Tree Paths
- script中获取input节点
- Editor_EditorPrefs,EditorUtility学习05
- 版本控制:git提交代码
- xib storyBoard IBOutlet连出来的视图属性为什么可以被设置成weak
- response
- Eclipse官方下载
- Static关键字在Java中的具体用法总结
- docker前身今世