AcWing
  • 首页
  • 题库
  • 题解
  • 分享
  • 问答
  • 活动
  • 应用
  • 吐槽
  • 登录/注册

LeetCode 257. 【递归】二叉树的所有路径    原题链接    简单

作者: 作者的头像   开水白菜 ,  2021-01-21 00:23:36 ,  阅读 29


1


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        string s;
        dfs(root,s,res);
        return res;

    }
    void dfs(TreeNode* root, string s, vector<string>& res){
        if(root == nullptr){ 
            return;
        }
        else s+=to_string(root->val);
        if(root->left && root->right ){
            s+="->";
            dfs(root->left,s,res);
            dfs(root->right,s,res);    
        }
        else if(root->left || root->right){
            s+="->";
            if(root->left) dfs(root->left,s,res);
            if(root->right) dfs(root->right,s,res);
        } 
        else res.emplace_back(s);
    }
};

0 评论

你确定删除吗?

© 2018-2021 AcWing 版权所有  |  京ICP备17053197号-1
联系我们  |  常见问题
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息