(201/212 passed) What is wrong with my code? [Javascript]


  • 1
    K

    Input: [3,9,8,4,0,1,7,null,null,null,2,5]
    Output:
    [[4],[9,5],[3,0,1],[2,8],[7]] Expected: [[4],[9,5],[3,0,1],[8,2],[7]]

    If the order of nodes appear in the same vertical order should be in the top to bottom order. The input shows node 8 is closer to the root node, thus should appear before 2. I don't understand why in my result it appears 2 before 8, other nodes are in order through. See my code below.

    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[][]}
     */
    var verticalOrder = function(root) {
        var store =  {};
    	traverse(root, 0, store);
    	var columnKey = Object.keys(store).sort(function(a,b){return a - b});
    	var results = [];
    	for(var i = 0; i < columnKey.length; i++){
    		results.push(store[columnKey[i]]);
    	}
    	return results
    };
    
    var traverse = (node, count, columns) => {
    	if(!node) return;
    	if(columns[count]) columns[count].push(node.val);
    	else columns[count] = [node.val];
    	if(node.left) traverse( node.left, count-1 ,columns)
    	if(node.right) traverse(node.right, count+1,  columns)
    }

  • 0
    I

    I had the same problem.
    You used pre-order traversal. 2 is in root.left and 8 is in root.right, thus 2 will always appear before 8.


  • 0
    T

    I had the same problem, just use preorder traverse and get the same error.


Log in to reply
 

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