描述
中文
English
给一棵二叉树,找出从根节点到叶子节点的所有路径。
class Solution {
public:
/**
* @param root: the root of the binary tree
* @return: all root-to-leaf paths
*/
vector<string>ans;
void dfs(TreeNode * node,string path)
{
cout<<node->val<<endl;
if(node==NULL) return ;
if(path=="") path=path+to_string(node->val);
else path =path+"->"+to_string(node->val);
if(node->left!=NULL) dfs(node->left,path);
if(node->right!=NULL) dfs(node->right,path);
if(node ->left==NULL && node->right==NULL) ans.push_back(path);
}
vector<string> binaryTreePaths(TreeNode * root)
{
// write your code here
if(root==NULL) return ans;
dfs(root,"");
return ans;
}
};