(91)257. 二叉树的所有路径(leetcode)

tech2025-07-31  20

题目链接: https://leetcode-cn.com/problems/binary-tree-paths/ 难度:简单 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 { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> ans; if(root==NULL){ return ans; } string s=""; dfs(ans,root,s); return ans; } void dfs(vector<string> &ans,TreeNode* root,string s){ if(root->left==NULL&&root->right==NULL){ s+=to_string(root->val); ans.push_back(s); }else{ s+=(to_string(root->val)+"->"); if(root->left!=NULL){ dfs(ans,root->left,s); } if(root->right!=NULL){ dfs(ans,root->right,s); } } } }; class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> ans; if(root==NULL){ return ans; } queue<TreeNode*> que; queue<string> path; que.push(root); path.push(""); while(!que.empty()){ TreeNode* t=que.front(); string s=path.front(); que.pop(); path.pop(); if(t->left==NULL&&t->right==NULL){ s+=to_string(t->val); ans.push_back(s); }else{ s+=(to_string(t->val)+"->"); if(t->left!=NULL){ que.push(t->left); path.push(s); } if(t->right!=NULL){ que.push(t->right); path.push(s); } } } return ans; } };
最新回复(0)