题解 | #二叉树根节点到叶子节点的所有路径和#
二叉树根节点到叶子节点的所有路径和
http://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
public int total = 0;
/**
*
* @param root TreeNode类
* @return int整型
*/
public int sumNumbers (TreeNode root) {
// write code here
if (null == root) {
return 0;
}
process(root, "");
return total;
}
public void process(TreeNode node, String str) {
str += node.val;
if (null == node.left && null == node.right) {
total += Integer.valueOf(str);
return;
}
if (null != node.left) {
process(node.left, str);
}
if (null != node.right) {
process(node.right, str);
}
str.substring(0, str.length() - String.valueOf(node.val).length());
}
}