题目:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
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> res, left, right;
if (root == NULL) {
return res;
}
if (root->left == NULL && root->right == NULL) {
//print the answer
res.push_back(to_string(root->val));
} else {
if (root->left) {
left = binaryTreePaths(root->left);
for (int i = 0; i < left.size(); i++) {
left[i] = to_string(root->val) + "->" + left[i];
res.push_back(left[i]);
}
}
if (root->right) {
right = binaryTreePaths(root->right);
for (int i = 0; i < right.size(); i++) {
right[i] = to_string(root->val) + "->" + right[i];
res.push_back(right[i]);
}
}
}
return res;
}
};
答案二:
/**
* 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;
}
binaryTreePaths(res, root, to_string(root->val));
return res;
}
void binaryTreePaths(vector<string>& res, TreeNode* node, string s) {
if (node->left == NULL && node->right == NULL) {
res.push_back(s);
return;
} else {
if (node->left) {
binaryTreePaths(res, node->left, s + "->" + to_string(node->left->val));
}
if (node->right) {
binaryTreePaths(res, node->right, s + "->" + to_string(node->right->val));
}
}
}
};