Tuesday, April 19, 2016

LeetCode Q257: Binary Tree Paths


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

Solution:
/**
* 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:
/**
* 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;
}
};
view raw Q257Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment