Sum Root to Leaf Numbers

https://www.lintcode.com/problem/sum-root-to-leaf-numbers/description

/**
 * Definition of TreeNode:
 * public class TreeNode {
 * public int val;
 * public TreeNode left, right;
 * public TreeNode(int val) {
 * this.val = val;
 * this.left = this.right = null;
 * }
 * }
 */

public class Solution {
    private int sum = 0;
    /**
     * @param root: the root of the tree
     * @return: the total sum of all root-to-leaf numbers
     */
    public int sumNumbers(TreeNode root) {
        // write your code here
        tree(root, "");
        return sum;
    }

    private void tree(TreeNode root, String s) {
        if (root == null) {
            return;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        s += root.val;
        if (right == null && left == null) {
            sum += Integer.parseInt(s);
        } else {
            tree(left, s);
            tree(right, s);
        }
    }
}

你可能感兴趣的:(Sum Root to Leaf Numbers)