[leetcode] Sum Root to Leaf Numbers
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
思路:递归求解,传递每个路程的和,到叶子节点累加到结果中。
public class Solution { private int res; public int sumNumbers(TreeNode root) { count(root, 0); return res; } private void count(TreeNode root, int pre) { if (root == null) return; int cur = pre * 10 + root.val; if (root.left == null && root.right == null) { res += cur; return; } count(root.left, cur); count(root.right, cur); } public static void main(String[] args) { TreeNode root = new TreeNode(5); root.left = new TreeNode(1); root.left.left = new TreeNode(2); root.left.right = new TreeNode(3); root.right = new TreeNode(2); System.out.println(new Solution().sumNumbers(root)); } }

浙公网安备 33010602011771号