257. Binary Tree Paths

来源:互联网 发布:mac 删除桌面文件夹 编辑:程序博客网 时间:2024/05/22 08:02

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

/** * 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> result;    if(root==NULL) return result;    dfs(root,to_string(root->val),result);    return result;    }    void dfs(TreeNode* root,string s1,vector<string>& result)    {        if(root->left==NULL&&root->right==NULL)        {            result.push_back(s1);            return ;        }        if(root->left) dfs(root->left,s1+"->"+to_string(root->left->val),result);        if(root->right) dfs(root->right,s1+"->"+to_string(root->right->val),result);        return ;    }};

0 0