[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"]
给一个二叉树,返回所有根到叶节点的路径。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> list = new ArrayList<>(); binaryTreePathsHelper(root, list, new String()); return list; } public void binaryTreePathsHelper(TreeNode root, List<String> list, String string) { if (root == null ) { return ; } if (root.left == null && root.right == null ) { string = string + root.val; list.add(string); return ; } binaryTreePathsHelper(root.left, list, string + root.val + "->" ); binaryTreePathsHelper(root.right, list, string + root.val + "->" ); } } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class Solution: # @param {TreeNode} root # @return {string[]} def binaryTreePaths( self , root): result, path = [], [] self .binaryTreePathsRecu(root, path, result) return result def binaryTreePathsRecu( self , node, path, result): if node is None : return if node.left is node.right is None : ans = "" for n in path: ans + = str (n.val) + "->" result.append(ans + str (node.val)) if node.left: path.append(node) self .binaryTreePathsRecu(node.left, path, result) path.pop() if node.right: path.append(node) self .binaryTreePathsRecu(node.right, path, result) path.pop() |
C++: DFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Solution { public : vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (root) dfs(root, "" , res); return res; } void dfs(TreeNode *root, string out, vector<string> &res) { out += to_string(root->val); if (!root->left && !root->right) res.push_back(out); else { if (root->left) dfs(root->left, out + "->" , res); if (root->right) dfs(root->right, out + "->" , res); } } }; |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution { public : vector<string> binaryTreePaths(TreeNode* root) { if (!root) return {}; if (!root->left && !root->right) return {to_string(root->val)}; vector<string> left = binaryTreePaths(root->left); vector<string> right = binaryTreePaths(root->right); left.insert(left.end(), right.begin(), right.end()); for ( auto &a : left) { a = to_string(root->val) + "->" + a; } return left; } }; |
类似题目:
[LeetCode] 113. Path Sum II 路径和 II
[LeetCode] 437. Path Sum III 路径和 III
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步