题目:
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:
void travel(TreeNode* root, string str)
{
string tmp = str;
if(root->left == NULL && root->right == NULL)
{
path.push_back(str);
return;
}
if(root->left)
{
str = tmp + "->" + to_string(root->left->val);
travel(root->left,str);
}
if(root->right)
{
str = tmp + "->" + to_string(root->right->val);
travel(root->right,str);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if(!root)
return path;
travel(root,to_string(root->val));
return path;
}
private:
vector<string> path;
};