Invert Binary Tree : Wrong specs in JS ?

  • 6

    in the JS version of the Inver Binary Tree problem, it's written that you should get a binary tree in the form of an object, but they give it to you as an array. Is it normal ?

    Screenshot of the problem

  • 3

    I'm not an expert in how the Javascript submissions are judged on OJ, but if it is like other available languages here, then the tree is only displayed in the form of array for readers' convenience. In memory, it is really a dynamically linked structure. For this problem, you are not supposed to create your own data structure, nor even create instances of the predefined TreeNode type. Instead, swap the children of root, then return root itself.

  • 2

    Interesting. I tried javascript for the first time on leetcode and it runs faster than my Java version. lol

    Basically, just like @stellari said, "you are not supposed to create your own data structure".

    your newTree should be defined as:

    var newTree=new TreeNode(root.val);
    newTree.left = invertTree(root.right);
    newTree.right = invertTree(root.left);

    Besides, lots of people use swap, which avoids new "instances of the predefined TreeNode type".

    var temp = root.left;
    root.left = root.right;
    root.right = temp;
    return root;

Log in to reply

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