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;
    }
};
原文地址:https://www.cnblogs.com/zengzy/p/5054333.html