首页 > 代码库 > 257. Binary Tree Paths
257. Binary Tree Paths
<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px "Helvetica Neue"; color: #323333 }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px "Helvetica Neue"; color: #323333; min-height: 16.0px }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Menlo; color: #323333; background-color: #f5f5f5 }
span.s1 { }</style>
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"]
Solution1: dfs, recursion. use the dfs function.
1 class Solution { 2 public: 3 vector<string> binaryTreePaths(TreeNode* root) { 4 vector<string> res; 5 if (!root) return res; 6 dfs(res,root,to_string(root->val)); 7 return res; 8 } 9 10 void dfs(vector<string> res, TreeNode* root, string path){ 11 if (!root->left && !root->right){ 12 res.push_back(path); 13 return; 14 } 15 if (root->left) dfs(res,root->left,path+"->"+to_string(root->left->val)); 16 if (root->right) dfs(res, root->right, path+"->"+to_string(root->right->val)); 17 } 18 };
257. Binary Tree Paths
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。