力扣-257题 二叉树的所有路径(C++)- 回溯+递归+有价值

题目链接:https://leetcode-cn.com/problems/binary-tree-paths/
题目如下:
在这里插入图片描述
在这里插入图片描述

/**
 * 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> result;
        vector<int> path;
        if(root==NULL) return result;
        dfs(root,path,result);
        return result;
    }

    void dfs(TreeNode* root,vector<int>& path,vector<string>& result){
        
        path.push_back(root->val);

        //终止条件:当找到叶子节点的时候,就将路径放入到result中
        //即root->left==NULL&&root->right==NULL
        if(root->left==NULL&&root->right==NULL){//遇到叶子节点,将路径放入result
            string str_path="";
            for(int e:path)
            str_path+=to_string(e)+"->";

            str_path[str_path.size()-1]=str_path[str_path.size()-2]=0;//去掉多余的->

            result.push_back(str_path);
            return ;
        }

        //单层逻辑(前序遍历——根左右)
        if(root->left){
            dfs(root->left,path,result);
            path.pop_back();
        }
        if(root->right){
            dfs(root->right,path,result);
            path.pop_back();
        }

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值