leetcode+ 二叉树root->root的所有路径存储,递归

https://leetcode.com/problems/binary-tree-paths/description/

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

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/81150909
今日推荐