1.描述
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"]
2.分析
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> vec;
if (root == NULL) return vec;
stringstream ss;
ss << root->val;
string str = ss.str();
if (root->left == NULL && root->right == NULL) {
vec.push_back(str);
}
if (root->left) visitTreeNodes(root->left, vec, str);
if (root->right) visitTreeNodes(root->right, vec, str);
return vec;
}
private:
void visitTreeNodes(TreeNode* root, vector<string> &vec, string str) {
str += "->";
stringstream ss;
ss << root->val;
str += ss.str();
if (root->left == NULL && root->right == NULL) {
vec.push_back(str);
return ;
}
if (root->left) visitTreeNodes(root->left, vec, str);
if (root->right) visitTreeNodes(root->right, vec, str);
}
};