257 Binary Tree Paths
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:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if ( root == NULL ) return res;
vector<string> res1 = binaryTreePaths(root->left);
vector<string> res2 = binaryTreePaths(root->right);
int n1 = res1.size(), n2 = res2.size();
if ( n1 == 0 and n2 == 0 ) res.push_back(to_string(root->val));
if ( n1 != 0 ) {
for ( int i = 0; i <= n1-1; i++ ) {
res.push_back(to_string(root->val) + "->" + res1[i]);
}
}
if ( n2 != 0 ) {
for ( int i = 0; i <= n2-1; i++ ) {
res.push_back(to_string(root->val) + "->" + res2[i]);
}
}
return res;
}
};
Notes
Note the special case of leaf node!