A simple Java solution


  • 1
    H
    public class Solution {
        public int sumNumbers(TreeNode root) {
            if (root == null) {
                return 0;
            }
            return sum(root, 0);
        }
        private int sum(TreeNode root, int sum) {
            if (root == null) {
                return 0;
            }
            if (root.left == null && root.right == null) {
                return sum + root.val;
            }
            return sum(root.right, (sum + root.val) * 10) + sum(root.left, (sum + root.val) * 10);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.