【LeetCode刷题(简单程度)】257. 二叉树的所有路径

tech2026-01-17  4

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1  /   \ 2     3  \   5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

思路: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: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if(root == nullptr) { return res; } DFS(root, res, ""); return res; } void DFS(TreeNode* root,vector<string>& res,string path)//先序遍历 { path += to_string(root->val);//用path遍历记录路径 if(!root->left&&!root->right)//当我们确实遍历到了叶子节点 { res.push_back(path);//则加入结果集 return; } if(root->left)//往左子树递归 { DFS(root->left,res,path+"->"); } if(root->right)//往右子树递归 { DFS(root->right,res,path+"->"); } } };

 

最新回复(0)