package leetcode;
/*Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.*/
public class Sum_root_to_leaf_numbers {
public static void main(String[] args) {
}
int sum = 0; //设为全局变量这样不会在调用过程中释放
public int sumNumbers(TreeNode root) {
if(root == null) //遇到空节点时,就返回.注意每个叶子节点的左右节点都为空节点
return sum;
if(root.left == null && root.right == null) { //叶子节点,就把现在叶子节点的值(其实是路径上计算过来的结果)加到sum变量中
sum +=root.val;
}
if(root.left != null)
root.left.val += root.val*10; //当左子节点不为空,则计算结果替换左子节点的值
if(root.right != null)
root.right.val += root.val*10; //当右子节点不为空,则计算结果替换右子节点的值
sumNumbers(root.left); //递归对左子节点,直到遇到空节点为止
sumNumbers(root.right); //递归对右子节点,直到遇到空节点为止
return sum;
}
}