Leetcode 257. 二叉树的所有路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Bendaai/article/details/81541089

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:
    string tmp;
    vector<string> ans;
    void dfs(TreeNode* root) {
        if(!root->left && !root->right){
            ans.push_back(tmp);
            return;
        }
        string k=tmp;
        if(root->left) tmp+="->"+to_string(root->left->val),dfs(root->left),tmp=k;
        if(root->right) tmp+="->"+to_string(root->right->val),dfs(root->right),tmp=k;

    }
    vector<string> binaryTreePaths(TreeNode* root) {
        if(!root) return ans;
        tmp+=to_string(root->val);
        dfs(root);
        return ans;
    }
};
展开阅读全文

没有更多推荐了,返回首页