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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| package com.lyloou.tool.tree;
import java.util.ArrayList; import java.util.List;
public class Solution2 { public static void main(String[] args) { test1(); test2(); }
private static void test1() { TreeNode a = new TreeNode(1); TreeNode b = new TreeNode(2); TreeNode c = new TreeNode(3); TreeNode d = new TreeNode(5); a.left = b; a.right = c; b.right = d; System.out.println(binaryTreePaths(a)); }
private static void test2() { TreeNode a1 = new TreeNode(1); TreeNode a2 = new TreeNode(2); TreeNode a3 = new TreeNode(3); TreeNode a4 = new TreeNode(4); TreeNode a5 = new TreeNode(5); TreeNode a6 = new TreeNode(6); TreeNode a7 = new TreeNode(7); a1.left = a2; a1.right = a3; a2.left = a4; a2.right = a5; a3.left = a6; a3.right = a7; System.out.println(binaryTreePaths(a1)); }
private static List<String> binaryTreePaths(TreeNode root) { if (root == null) { return new ArrayList<>(); } if (isLeaf(root)) { List<String> list = new ArrayList<>(); list.add(root.val + ""); return list; }
final List<String> leftList = binaryTreePaths(root.left); for (int i = 0; i < leftList.size(); i++) { leftList.set(i, root.val + "->" + leftList.get(i)); }
final List<String> rightList = binaryTreePaths(root.right); for (int i = 0; i < rightList.size(); i++) { rightList.set(i, root.val + "->" + rightList.get(i)); }
List<String> result = new ArrayList<>(leftList.size() + rightList.size()); result.addAll(leftList); result.addAll(rightList); return result; }
private static boolean isLeaf(TreeNode node) { return node.left == null && node.right == null; }
static class TreeNode { public int val; public TreeNode left, right;
public TreeNode(int val) { this.val = val; this.left = this.right = null; } } }
|