题解 | #二叉树根节点到叶子节点的所有路径和# 递归
二叉树根节点到叶子节点的所有路径和
https://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { int sum = 0; public void reachLeaf(TreeNode root, int num) { if (root == null) { return; } else if (root.left == null && root.right == null) { int t = num + root.val; sum += t; reachLeaf(root.left, t * 10); reachLeaf(root.right, t * 10); } else { int t = num + root.val; // sum += t; reachLeaf(root.left, t * 10); reachLeaf(root.right, t * 10); } } public int sumNumbers (TreeNode root) { reachLeaf(root, 0); return sum; } }
节点的值,每下一层,等于上一层计算的值 * 10 + 叶子节点的值,区别处理叶子节点和非叶节点即可。