题解 | #二叉树根节点到叶子节点的所有路径和#
二叉树根节点到叶子节点的所有路径和
http://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public int sumNumbers (TreeNode root) {
// write code here
if (root == null) {
return 0;
}
doSumNumbers(root, "0");
return sum;
}
Integer sum = 0;
// 先序遍历二叉树,遇到子树左右节点为空,则表示到叶子节点。
public void doSumNumbers(TreeNode root, String before) {
// write code here
String num = String.valueOf(root.val);
if (root.left == null && root.right == null) {
sum += Integer.parseInt(before + num);
System.out.println(sum);
}
if (root.left != null) {
doSumNumbers(root.left, before + num);
}
if (root.right != null) {
doSumNumbers(root.right, before + num);
}
}
}