LeetCode 257. Binary Tree Paths

2020-04-21 10:44:54 浏览数 (1)

题目

代码语言:javascript复制
/**
 * 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 "->");
    }
};

0 人点赞