LeetCode 257. Binary Tree Paths

it2025-07-17  8

题目:

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3

打印binary tree的所有根到叶子的路径,感觉和之前做的path sum 2差不多,也是用到了一点回溯的思想。helper function里先把当前节点加入temp,然后check如果root是叶子的话就把当前路径加到result里,如果不是叶子的话就要左右两边分别继续递归,递归完了要记得remove掉。

Runtime: 1 ms, faster than 99.98% of Java online submissions for Binary Tree Paths.

Memory Usage: 39.5 MB, less than 7.90% of Java online submissions for Binary Tree Paths.

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> result = new ArrayList<>(); if (root == null) { return result; } helper(root, new ArrayList<>(), result); return result; } public void helper(TreeNode root, List<Integer> temp, List<String> result) { temp.add(root.val); if (root.left == null && root.right == null) { StringBuilder sb = new StringBuilder(); for (int i : temp) { sb.append(i); sb.append("->"); } result.add(sb.substring(0, sb.length() - 2).toString()); return; } if (root.left != null) { helper(root.left, temp, result); temp.remove(temp.size() - 1); } if (root.right != null) { helper(root.right, temp, result); temp.remove(temp.size() - 1); } } }

看了下https://leetcode.wang/leetcode-257-Binary-Tree-Paths.html发现人家并不用回溯remove?我也不是很懂了,暂时不想研究了。

最新回复(0)