Binary Tree Paths
Binary Tree Paths
Total Accepted: 26174 Total Submissions: 104545 Difficulty: Easy
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 binaryTreePaths(TreeNode* root,vector<string>& paths,string path){ if(!root) return; int path_size = path.size(); string valstr = path_size ==0 ? to_string(root->val) : "->"+to_string(root->val); path.append(valstr.begin(),valstr.end()); if(root->left==NULL && root->right==NULL){ paths.push_back(path); return; } binaryTreePaths(root->left,paths,path); binaryTreePaths(root->right,paths,path); } vector<string> binaryTreePaths(TreeNode* root) { vector<string> paths; string path; binaryTreePaths(root,paths,path); return paths; } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记