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;
    }
};
posted @ 2018-08-01 18:15  一条图图犬  阅读(266)  评论(0编辑  收藏  举报