码迷,mamicode.com
首页 > 其他好文 > 详细

257. Binary Tree Paths

时间:2017-05-11 13:30:46      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:str   path   use   roo   node   for   ack   logs   ica   

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

标签:str   path   use   roo   node   for   ack   logs   ica   

原文地址:http://www.cnblogs.com/anghostcici/p/6840406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!