I apply BFS, and StringBuilder to solve this problem. But i get a time error


  • 0
    X

    public class Solution {
    public int sumNumbers(TreeNode root) {
    // BFS keep record of each level
    if (root == null){
    return 0;
    }
    LinkedList<TreeNode> list = new LinkedList<TreeNode>();

        LinkedList<StringBuilder> sumlist = new LinkedList<StringBuilder>();
        String s1 = String.valueOf(root.val);
        StringBuilder s = new StringBuilder(s1);
        sumlist.add (s);
        list.add(root);
        int sum = 0;
        while(!list.isEmpty()){
            TreeNode n = list.poll();
            StringBuilder numString = sumlist.poll();
            if (n.left == null && n.right == null){
                sum += Integer.parseInt(numString.toString());
            }
            if(n.left != null){
                StringBuilder num1 = sumlist.poll();
                sumlist.add(num1.append(n.left.val));
                list.add(n.left);
            }
            
            if (n.right != null){
                StringBuilder num2 = sumlist.poll();
                sumlist.add(num2.append(n.right.val));
                list.add(n.right);
            }
        }
        
        return sum;
        
    }
    

    }


Log in to reply
 

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