[LeetCode] Binary Tree Paths

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 };

 

posted @ 2015-08-16 10:48  jianchao-li  阅读(336)  评论(0编辑  收藏  举报