LeetCode 257. Binary Tree Paths

题目

/**
 * 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:
    vector<string> ans;
    vector<string> binaryTreePaths(TreeNode* root) {
        
        if(root!=NULL)
            dfs(root,"");
        return ans;
        
    }
    
    void dfs(TreeNode* root,string path)
    {
        path+=to_string(root->val);
        if(root->left==NULL&&root->right==NULL)
        {
            ans.push_back(path);
            return;
        }

        if(root->left!=NULL)
            dfs(root->left,path+"->");
        if(root->right!=NULL)
            dfs(root->right,path+"->");
    }
};
原文地址:https://www.cnblogs.com/dacc123/p/12724530.html