Easy to understand Java solution


  • 0
    C
    int sum = 0;
        public int sumNumbers(TreeNode root) {
            if(root == null) return 0;
            getSumAlong(root, "");
            return sum;
        }
        
        private void getSumAlong(TreeNode node, String str) {
            str = str + node.val;
            if(node.left == null && node.right == null) {
                sum += Integer.parseInt(str);
                return;
            }
            if(node.left != null) getSumAlong(node.left, str);
            if(node.right != null) getSumAlong(node.right, str);
        }

  • 0
    Y

    string modification is expensive, try using StringBuilder object; also, can you avoid using a global variable?


Log in to reply
 

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