LeetCode 257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: 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 { //树的遍历dfs
public:
    vector<string> ans;
    void dfs(TreeNode* root, string path){
        if(root){
            path+="->";
            path+=to_string(root->val);
        }else
            return ;
        if(root->left)
            dfs(root->left, path);
        if(root->right)
            dfs(root->right, path);
        if(!root->left&&!root->right)
            ans.push_back(path.substr(2,path.length()-2));
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        string path="";
        dfs(root, path);
        return ans;
    }
};
posted @ 2018-12-03 15:15  A-Little-Nut  阅读(90)  评论(0编辑  收藏  举报