Binary Tree Paths @LeetCode
PROBLEM :
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"]
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* 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> vec ;
if(root==NULL)
return vec ;
string str="" ;
CheckAllPaths(root,str,vec) ;
return vec ;
}
void CheckAllPaths(TreeNode *root,string str,vector<string> &vec){
if(root==NULL)
return ;
if(str=="")
str+=to_string(root->val) ;
else{
str+="->" ;
str+=to_string(root->val) ;
}
if(root->left==NULL&&root->right==NULL)
vec.push_back(str) ;
CheckAllPaths(root->left,str,vec) ;
CheckAllPaths(root->right,str,vec) ;
}
};
---------------------------------------------------------------------------------
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"]
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* 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> vec ;
if(root==NULL)
return vec ;
string str="" ;
CheckAllPaths(root,str,vec) ;
return vec ;
}
void CheckAllPaths(TreeNode *root,string str,vector<string> &vec){
if(root==NULL)
return ;
if(str=="")
str+=to_string(root->val) ;
else{
str+="->" ;
str+=to_string(root->val) ;
}
if(root->left==NULL&&root->right==NULL)
vec.push_back(str) ;
CheckAllPaths(root->left,str,vec) ;
CheckAllPaths(root->right,str,vec) ;
}
};
---------------------------------------------------------------------------------
Comments
Post a Comment