码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的所有路径

时间:2020-03-15 13:13:41      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:解释   col   struct   val   style   roo   ini   node   返回   

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

1
/ \
2 3
\
5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

code:

/**
 * 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 {
private:
    void binaryTreePathsCore(TreeNode* root,string path,vector<string>& res)
    {
        if(root==nullptr)
            return ;
        
        path+=to_string(root->val);
        if(root->left==nullptr&&root->right==nullptr)
        {
            res.push_back(path);
            return ;
        }
        binaryTreePathsCore(root->left,path+"->",res);
        binaryTreePathsCore(root->right,path+"->",res);
    }
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        if(!root)
            return {};
        
        string path;
        vector<string> res;
        binaryTreePathsCore(root,path,res);
        return res;
    }
};

 

二叉树的所有路径

标签:解释   col   struct   val   style   roo   ini   node   返回   

原文地址:https://www.cnblogs.com/tianzeng/p/12496842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!