题意:求出从根结点到叶结点的所有路径。
思路:DFS。
/**
* 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> re;
vector<string> binaryTreePaths(TreeNode* root) {
if(root == NULL) return re;
string p;
p += to_string(root->val);
if(root->left == NULL && root->right == NULL) re.push_back(p);
if(root->left) dfs(p, root->left);
if(root->right) dfs(p, root->right);
return re;
}
void dfs(string p, TreeNode* root) {
if(root == NULL) return;
if(root->left == NULL && root->right == NULL) {
p += "->";
p += to_string(root->val);
re.push_back(p);
return;
}
p += "->";
p += to_string(root->val);
if(root->left) dfs(p, root->left);
if(root->right) dfs(p, root->right);
return;
}
};