leetcode 257. 二叉树的所有路径

tech2025-06-07  9

leetcode 257. 二叉树的所有路径

题目详情

题目链接 给定一个二叉树,返回所有从根节点到叶子节点的路径。 说明: 叶子节点是指没有子节点的节点。

示例: 输入: 1 / 2 3 \ 5 输出: [“1->2->5”, “1->3”] 解释: 所有根节点到叶子节点的路径为: 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 { private: vector<string> results; public: void preOrder(TreeNode *root, string &result) { if (root) { auto temp = result; temp += std::to_string(root->val); if (!root->left && !root->right) { results.push_back(temp); return; } temp += "->"; if (root->left) { preOrder(root->left, temp); } if (root->right) { preOrder(root->right, temp); } } } vector<string> binaryTreePaths(TreeNode* root) { string result; preOrder(root, result); return results; } };

我的成绩

执行结果:通过 执行用时:4 ms, 在所有 C++ 提交中击败了89.73%的用户 内存消耗:13.7 MB, 在所有 C++ 提交中击败了68.43%的用户

一些想法

本道题进行先序遍历即可。

执行用时为 0 ms 的范例

/** * 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> binaryTreePaths(TreeNode* root) { vector<string> res; if(root == NULL)return res; if(root->left == NULL && root->right == NULL){ res.push_back(to_string(root->val)); return res; } vector<string> resL = binaryTreePaths(root->left); for(int i = 0; i < resL.size(); i++){ res.push_back(to_string(root->val) + "->" + resL[i]); } vector<string> resR = binaryTreePaths(root->right); for(int i = 0; i < resR.size(); i++){ res.push_back(to_string(root->val) + "->" + resR[i]); } return res; } };

思考

参见官方解答

最新回复(0)