Sum Root to Leaf Numbers 2021-12-20 05:34

Problem Description

public int sumNumbers(TreeNode root) {
    return sum(root, 0);
}

private int sum(TreeNode root, int currentVal) {
    if (root == null) {
        return 0;
    }
    currentVal = currentVal * 10 + root.val;
    if (root.left == null && root.right == null) {
        return currentVal;
    } else {
        return sum(root.left, currentVal) + sum(root.right, currentVal);
    }
}
Runtime Memory
0 ms 35.7 MB

henryxi leetcode list

EOF