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
| * 树结点 */ static class TreeNode { int val; TreeNode left; TreeNode right;
public TreeNode(int val) { this.val = val; }
public TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }
* 寻找路径 */ public static void findPath(TreeNode root, int sum) { if (root == null) return; Stack<Integer> paths = new Stack<Integer>(); findPath(root, paths, sum, 0); }
* 递归寻找路径 */ private static void findPath(TreeNode root, Stack<Integer> paths, int sum,int currentSum) { currentSum += root.val; boolean isLeaf = root.left == null && root.right == null; paths.push(root.val); if (isLeaf && currentSum == sum) { printPath(paths); } if (root.left != null) { findPath(root.left, paths, sum, currentSum); } if (root.right != null) { findPath(root.right, paths, sum, currentSum); } paths.pop(); }
* 打印路径 */ static void printPath(Stack<Integer> paths) { if (paths.isEmpty()) return; for (Integer item : paths) { System.out.print(item + " - "); } System.out.println(); }
|