题目:
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
.
题意及分析:给出一棵二叉树,每个节点的值均为0-9,根节点到叶子节点上的值组成一个数字,遍历树,求根节点到所有叶子结点的数字之和。使用先序遍历,用一个变量count储存到每个非叶子结点得到的值,对于每个叶子结点将父节点的值*10+本节点的值就得到根节点到该叶子结点的值,加到和sum里面即可。
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int sumNumbers(TreeNode root) { if(root==null) return 0; int[] nums = new int[1]; //保存sum的值, build(nums,root,0); return nums[0]; } public void build(int[] sum,TreeNode node,int temp){ int count = temp; if(node.left==null&&node.right==null){ //叶子节点计算值 sum[0] += count*10+node.val; return; } count = count*10+node.val; //记录每个非叶子节点的值 if(node.left!=null){ build(sum,node.left,count); } if(node.right!=null){ build(sum,node.right,count); } } }