Total Accepted: 44011 Total Submissions: 155436 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"]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 helper(TreeNode* root, vector<string>& res, string curStr){ | |
if(!root) | |
return; | |
if(!root->left&&!root->right){ | |
curStr=curStr+string("->")+to_string(root->val); | |
res.push_back(curStr); | |
return; | |
} | |
curStr=curStr+string("->")+to_string(root->val); | |
helper(root->left, res, curStr); | |
helper(root->right, res, curStr); | |
} | |
vector<string> binaryTreePaths(TreeNode* root) { | |
vector<string> res; | |
string curStr; | |
if(!root) | |
return res; | |
curStr=to_string(root->val); | |
if(!root->left&&!root->right){ | |
res.push_back(curStr); | |
return res; | |
} | |
helper(root->left, res, curStr); | |
helper(root->right, res, curStr); | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 helper(vector<string>& res, string tmpRes, TreeNode* root){ | |
if(root==NULL) | |
return; | |
tmpRes = tmpRes.length()==0? to_string(root->val):tmpRes+string("->")+to_string(root->val); | |
if(root->left==NULL&&root->right==NULL){ | |
res.push_back(tmpRes); | |
return; | |
} | |
helper(res, tmpRes, root->left); | |
helper(res, tmpRes, root->right); | |
} | |
vector<string> binaryTreePaths(TreeNode* root) { | |
vector<string> res; | |
string tmpRes; | |
helper(res, tmpRes, root); | |
return res; | |
} | |
}; |
No comments:
Post a Comment