LeetCode题解之Binary Tree Paths

时间:2023-11-11 08:36:20

1、题目描述

LeetCode题解之Binary Tree Paths

2、分析

使用递归。

3、代码

 vector<string> ans;

     vector<string> binaryTreePaths(TreeNode* root) {

         if (root == NULL) return ans;
leafPath(root,"");
return ans; } void leafPath(TreeNode *root, string s)
{
if (root == NULL)
return ;
if (root->left == NULL && root->right == NULL){
string stmp = s + to_string(root->val);
ans.push_back(stmp);
return ;
} else {
string stmp = s + to_string(root->val) + "->";
leafPath(root->left, stmp);
leafPath(root->right, stmp);
} }