Test case [5,1,6,null,3,null,null,2,4]


  • 0
    E

    I'm not sure what is wrong with my code, the test case is:

    Submission Result: Wrong Answer 
    Input:
    [5,1,6,null,3,null,null,2,4]
    Output:
    [[1,2],[5,3],[4,6]]
    Expected:
    [[1,2],[5,3],[6,4]]
    

    The code is:

    public List<List<Integer>> verticalOrder(TreeNode root) {
        final Map<Integer, List<Integer>> map = new HashMap<>();
        solve(root, 0, map);
        final List<Integer> sortedKeys = new ArrayList<>(map.keySet());
        Collections.sort(sortedKeys);
        final List<List<Integer>> result = new ArrayList<>();
        for (Integer i: sortedKeys) {
            result.add(map.get(i));
        }
        return result;
    }
    
    private void solve(TreeNode root, int seed, Map<Integer, List<Integer>> map) {
        if (root == null) {
            return;
        }
        if (!map.containsKey(seed)) {
            map.put(seed, new ArrayList<Integer>());
        }
        map.get(seed).add(root.val);
        solve(root.left, seed - 1, map);
        solve(root.right, seed + 1, map);
    }
    

    I run the above code in my IDE, build the tree regarding the input and have an expected output: [[1, 2], [5, 3], [6, 4]]. The order for 1,2 and 5,3 is right. So, I'm not sure how nodes 4 and 6 could be swapped. Can anyone see the issue in the code?


  • 1

    exactly same question here. Waiting . . .


  • 0
    S

    I've met this problem as well, then I changed my code to print nodes from top to bottom and left to right.
    In other words, use bfs instead of dfs.


Log in to reply
 

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