《LeetCode力扣练习》代码随想录——二叉树(二叉树的所有路径—Java)
刷题思路来源于 代码随想录
257. 二叉树的所有路径
-
二叉树-前序遍历
/** * 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; } List<Integer> path = new ArrayList<>(); recursion(root, path, result); return result; } private void recursion(TreeNode root, List<Integer> path, List<String> result) { path.add(root.val); if (root.left == null && root.right == null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < path.size() - 1; i++) { sb.append(path.get(i)).append("->"); } sb.append(path.get(path.size() - 1)); result.add(sb.toString()); return; } if (root.left != null) { recursion(root.left, path, result); path.remove(path.size() - 1); } if (root.right != null) { recursion(root.right, path, result); path.remove(path.size() - 1); } } }