257. Binary Tree Paths (树的路径)

 

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"]


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.res = []
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        def dfs(root,path):
            if root == None:
                return
            if root and root.left == None and root.right == None:
                path.append(str(root.val))
                self.res.append('->'.join(path))
            dfs(root.left,path+[str(root.val)])
            dfs(root.right,path+[str(root.val)])
        dfs(root,[])
        return self.res
            

 




 1 class Solution {
 2 public:
 3     vector<vector<int>> res;
 4     void backtrack(TreeNode* root, vector<int>& path) {  
 5         if (root == nullptr) return;
 6         if(root->left == nullptr && root->right == nullptr) {
 7             path.push_back(root->val);
 8             res.push_back(path);
 9             path.pop_back();
10             return;
11         }
12         path.push_back(root->val);
13         backtrack(root->left,path);
14         backtrack(root->right,path);
15         path.pop_back();
16     }
17     vector<string> binaryTreePaths(TreeNode* root) {
18         vector<string> final_res;
19         vector<int> path;
20         backtrack(root,path);
21         for(auto vec: res){
22             string path_str = "";
23             for(auto int i = 0;i < vec.size(); ++i){
24                 path_str.append(to_string(vec[i]));
25                 if (i != vec.size() - 1) path_str.append("->");
26             }
27             final_res.emplace_back(path_str);
28         }
29         return final_res;
30     }
31 };

 

 

posted @ 2017-11-03 09:46  乐乐章  阅读(153)  评论(0编辑  收藏  举报