257. Binary Tree Paths

来源:互联网 发布:校园网络诈骗小品剧本 编辑:程序博客网 时间:2024/06/06 16:42

题目:

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

["1->2->5", "1->3"]
思路:

本题还是利用递归的思想,具体思路可以参照以前写的一篇博客Path Sum,此处唯一要注意的是整形转换成字符串型to_sting()的使用

代码:

/** * 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> binaryTreePaths(TreeNode* root) {        vector<string> str(0);        if (root==NULL)            return str;                treetolist(root,str,to_string(root->val));        return str;    }private:    void treetolist(TreeNode* root,vector<string>& res,string s){        if(root->left==NULL&&root->right==NULL)        {            res.push_back(s);              return;        }        if(root->left)            treetolist(root->left,res, s + "->" + to_string(root->left->val));        if(root->right)            treetolist(root->right,res,s + "->" + to_string(root->right->val));    }};



原创粉丝点击