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

[LeetCode] Binary Tree Paths

时间:2015-08-16 11:58:51      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

The basic idea is to start from root and add it to the current path, then we recursively visit its left and right subtrees if they exist; otherwise, we have reached a leaf node, so just add the current path to the result paths.

The code is as follows.

 1 class Solution {
 2 public:
 3     vector<string> binaryTreePaths(TreeNode* root) {
 4         vector<string> paths;
 5         string path;
 6         treePaths(root, path, paths);
 7         return paths;
 8     }
 9 private:
10     void treePaths(TreeNode* node, string path, vector<string>& paths) {
11         if (!node) return;
12         path += path.empty() ? to_string(node -> val) : "->" + to_string(node -> val);
13         if (!(node -> left) && !(node -> right)) {
14             paths.push_back(path);
15             return;
16         }
17         if (node -> left) treePaths(node -> left, path, paths);
18         if (node -> right) treePaths(node -> right, path, paths);
19     }
20 };

 

[LeetCode] Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4733742.html

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