Solution using String


  • 0
    J

    The idea is very straightforward, collect the number represented by every path from root to leaf and sum them up. Does someone have better solution using String?

    public class Solution {
    public int sumNumbers(TreeNode root) {
        if (root == null) return 0;
        
        List<String> list = new ArrayList<String>();
        StringBuilder temp = new StringBuilder("");
        dfs(list, root, temp);
        int sum = 0;
        for (String i : list) {
            sum = sum + Integer.valueOf(i);
        }
        return sum;
    }
    
    private void dfs(List<String> list, TreeNode node, StringBuilder temp) {
        if (node == null) return;
        if (node.left == null && node.right == null) {
            temp.append(String.valueOf(node.val));
            list.add(temp.toString());
            return;
        } 
        
        temp.append(String.valueOf(node.val));
        int length = temp.length();
        
        dfs(list, node.left, temp);
        if (temp.length() > length) {
            temp.delete(length, temp.length());
        }
        dfs(list, node.right, temp);
    }
    

    }


Log in to reply
 

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