Problem
Solution
此题题意为,给定一棵二叉树,要求你找出所有根到叶节点的路径,题目也没有对访问次序做要求。
那么我们只要简单地对整棵树做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:
void dfs(vector<string> &ans,TreeNode* root,string path){
if(root==NULL) return;
path+=to_string(root->val);
if(root->left==NULL && root->right==NULL) ans.push_back(path);
else path+="->";
dfs(ans,root->left,path);
dfs(ans,root->right,path);
return;
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
string path="";
dfs(ans,root,path);
return ans;
}
};