129. 求根到叶子节点数字之和
题目来源
129. 求根到叶子节点数字之和
题目描述
题目解析
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int sum = 0;
public int sumNumbers(TreeNode root) {
helper(root, 0);
return sum;
}
private void helper(TreeNode root, int depth){
if (root == null){
return;
}
depth = depth * 10 + root.val;
if (root.left == null && root.right == null){
sum += depth;
return;
}
helper(root.left, depth);
helper(root.right, depth);
}
}
还没有评论,来说两句吧...