首页 > 其他 > 详细

257. Binary Tree Paths

时间:2017-09-28 14:40:19      阅读:270      评论:0      收藏:0      [点我收藏+]

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"]
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     void binaryTreePaths(TreeNode*root,vector<string>&res,string t)
13     {
14         if(!root->left&&!root->right)
15             res.push_back(t);
16         if(root->left)
17             binaryTreePaths(root->left,res,t+"->"+to_string(root->left->val));
18         if(root->right)
19             binaryTreePaths(root->right,res,t+"->"+to_string(root->right->val));
20     }
21     vector<string> binaryTreePaths(TreeNode* root) {
22         vector<string>res;
23          if(!root)
24              return res;
25         binaryTreePaths(root,res,to_string(root->val));
26         return res;
27     }
28 };

//如果有子节点,字符串随着递归一直累加,直到没有子节点,把累加的字符串存进字符串数组

257. Binary Tree Paths

原文:http://www.cnblogs.com/wangzao2333/p/7606538.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!