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.
思路: 每个节点表示的值为 上一个节点的基数 * 10 + 该节点的值,用一个变量sum(base)来记录上一个节点的基数
java代码:
- int helper(TreeNode root,int sum) {
- if(root==null) return sum;
- if(root.left==null && root.right==null) {
- return sum * 10 + root.val;
- }
- int left = 0;
- int right = 0;
- if(root.left!=null) {
- left = helper(root.left,sum*10+root.val);
- }
- if(root.right!=null) {
- right = helper(root.right,sum*10+root.val);
- }
- return left + right;
- }
- public int sumNumbers(TreeNode root) {
- if(root==null) return 0;
- if(root.left==null && root.right==null) return root.val;
- return helper(root,0);
- }

浙公网安备 33010602011771号