首页 > 其他 > 详细

LeetCode 257 二叉树所有路径

时间:2020-07-13 20:32:33      阅读:59      评论:0      收藏:0      [点我收藏+]

题目描述链接:https://leetcode-cn.com/problems/binary-tree-paths/

基本思路:从根节点一直向下深搜即可。当访问到叶子节点时结束。记录一下,可以使用to_string()函数隶属于string头文件,将int转换为string。具体LeetCode代码如下:

/**
 * 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>res;
    vector<string> binaryTreePaths(TreeNode* root) {
            string path="";
            dfs(root,path);
            return res;
    }
    void dfs(TreeNode* root,string path){
        if(!root){//防止整个树为空或者 非叶子节点只有一个子树的情况
            return;
        }
        if(!root->left&&!root->right){
            path+=to_string(root->val);
            res.push_back(path);
            return ;
        }   
        path+=to_string(root->val);
        path+="->";

        dfs(root->left,path);
        dfs(root->right,path);
    }
};

 

LeetCode 257 二叉树所有路径

原文:https://www.cnblogs.com/zzw-/p/13295293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!