257. Binary Tree Paths

来源:互联网 发布:淘宝情趣内衣买家秀 编辑:程序博客网 时间:2024/05/16 18:28

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”]

代码:

/** * 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:    void dfs(TreeNode* cur,string s,vector<string>&res)    {    if(cur->left==NULL&&cur->right==NULL)     {        res.push_back(s);        return;    }    if(cur->left!=NULL)    {        dfs(cur->left,s+"->"+to_string(cur->left->val),res);    }     if(cur->right!=NULL)    {        dfs(cur->right,s+"->"+to_string(cur->right->val),res);    }     }    vector<string> binaryTreePaths(TreeNode* root)     {    string s;    vector<string>res;    if(root==NULL) return res;    s+=to_string(root->val);    dfs(root,s,res);    return res;    }};
0 0
原创粉丝点击