Java solution, using Array to represent tree


  • 0
    X
        public int pathSum(int[] nums) {
            Integer[] tree = new Integer[16]; // TreeNode value could be `0`
            tree[0] = 0;
            for (int n : nums) {
                int depth = n / 100;
                int pos = (n % 100) / 10;
                int val = (n % 10);
                int index = (1 << depth - 1) + pos - 1;
                tree[index] = tree[index / 2] + val;
            }
    
            int total = 0;
            for (int i = 1; i < 16; i++) {
                if (tree[i] == null) continue;
                // index 8 to 15 represents depth 4
                if (i > 7 || tree[i * 2] == null && tree[i * 2 + 1] == null) {
                    total += tree[i];
                }
            }
            return total;
        }  
    

Log in to reply
 

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