NC_5_ALL_PATH_SUM
package org.example.interview.practice; /** * @author xianzhe.ma * @date 2021/8/21 */ public class NC_5_ALL_PATH_SUM { public static int sumNumbers(TreeNode root) { // write code here if (root == null) return 0; return backtrack(root, 0); } public static int backtrack(TreeNode root, int sum) { if (root == null) return sum; // 加入当前结点的值 sum = sum * 10 + root.val; if (root.left == null && root.right == null) { // 到叶子结点返回计算的值 return sum; } // 未到叶子结点,则往左右子节点继续计算和 return backtrack(root.left, sum) + backtrack(root.right, sum); } public static class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public static void main(String[] args) { TreeNode node0 = new TreeNode(4); TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); node0.right = node1; node0.left = node2; int result = sumNumbers(node0); System.out.println(result); } }