Binary Tree Paths

Binary Tree Paths

Total Accepted: 26174 Total Submissions: 104545 Difficulty: Easy

 

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.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    void binaryTreePaths(TreeNode* root,vector<string>& paths,string path){
        if(!root) return;
        
        int path_size = path.size();
        
        string valstr = path_size ==0 ? to_string(root->val) : "->"+to_string(root->val);
         
        path.append(valstr.begin(),valstr.end());
        
        if(root->left==NULL && root->right==NULL){
            paths.push_back(path);
            return;
        }
        
        binaryTreePaths(root->left,paths,path);
        binaryTreePaths(root->right,paths,path);
        
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> paths;
        string path;
        binaryTreePaths(root,paths,path);
        return paths;
    }
};
posted @ 2015-12-17 15:32  zengzy  阅读(177)  评论(0编辑  收藏  举报
levels of contents