leetcode257 C++ 4ms 二叉树的所有路径

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

        if(root->right != nullptr){
            recur(root->right, res, str + "->" + to_string(root->right->val));
        }
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(root == nullptr){
            return res;
        }
        recur(root, res, to_string(root->val));
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/theodoric008/p/9402846.html