LeetCode - Binary Tree Paths

解法一:recursion DFS

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

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/83048288