标签(空格分隔): LeetCode OJ BinaryTree
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”]
No doubt that we should use recursive method。
/**
* 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) {
if (root == NULL){
vector<string> empty;
return empty;
}
if (root->left == NULL && root->right == NULL){ // leaf
vector<string> path;
path.push_back(std::to_string(root->val));
return path;
}
vector<string> allPaths = combine(binaryTreePaths(root->left), binaryTreePaths(root->right)); // combine all subpaths
vector<string> result;
for (vector<string>::iterator it = allPaths.begin(); it != allPaths.end(); ++it){
result.push_back(std::to_string(root->val) + "->" + *it); // add current node to the paths
}
return result;
}
vector<string> combine(vector<string> left, vector<string> right){ // this is how to combine two vectors
vector<string> result;
result.reserve(left.size() + right.size() ); // preallocate memory
result.insert( result.end(), left.begin(), left.end() );
result.insert( result.end(), right.begin(), right.end() );
return result;
}
};