【LeetCode】257. Binary Tree Paths
题目:
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 recursiveTree(vector<string> &res, TreeNode* node, string str) { if (node->left == NULL && node->right == NULL) { res.push_back(str); return; } if (node->left != NULL) { recursiveTree(res, node->left, str + "->" + to_string(node->left->val)); } if (node->right != NULL) { recursiveTree(res, node->right, str + "->" + to_string(node->right->val)); } } vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (root == NULL) return res; recursiveTree(res, root, to_string(root->val)); return res; } };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步