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"]
代码
/**
* 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> results;
vector<int> path;
binaryTreePaths(root, path, results);
return results;
}
void binaryTreePaths(TreeNode* root, vector<int> path, vector<string>& results){
if(root == NULL){
//Error
return;
}
path.push_back(root->val);
if(root->left == NULL && root->right == NULL) {
//Leaf
string result;
int pSize = path.size();
for(int i=0; i<pSize; i++){
result += to_string(path[i]);
if(i != pSize - 1)
result += "->";
}
results.push_back(result);
} else {
if(root->left != NULL)
binaryTreePaths(root->left, path, results);
if(root->right != NULL)
binaryTreePaths(root->right, path, results);
}
}
};