257. Binary Tree Paths

来源:互联网 发布:成都java培训费用多少 编辑:程序博客网 时间:2024/06/08 20:08

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.


/** * 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 __binaryTreePaths(TreeNode* root, string str, vector<string>& res){if(!root){res.push_back(str);return;}str += to_string(root->val);if(!root->left && !root->right){__binaryTreePaths(root->right, str, res);}if(root->left){__binaryTreePaths(root->left, str + "->", res);}if(root->right){__binaryTreePaths(root->right, str + "->", res);}}vector<string> binaryTreePaths(TreeNode* root) {string str;vector<string> res;if(root){__binaryTreePaths(root, str, res);}return res;}};
写的还是不简洁
void binaryTreePaths(vector<string>& result, TreeNode* root, string t) {    if(!root->left && !root->right) {        result.push_back(t);        return;    }    if(root->left) binaryTreePaths(result, root->left, t + "->" + to_string(root->left->val));    if(root->right) binaryTreePaths(result, root->right, t + "->" + to_string(root->right->val));}vector<string> binaryTreePaths(TreeNode* root) {    vector<string> result;    if(!root) return result;        binaryTreePaths(result, root, to_string(root->val));    return result;}




原创粉丝点击