Simple JavaScript solution


  • 5
    L
    function invertTree(root) {
        if (root) {
            [root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
        }
        return root;
    }

  • 0
    U

    bro , can you explain this solution and give some example??
    i can not understand it...
    thx :-)


  • 0
    L

    There is just syntax sugar.

    It could be translated to

    function invertTree(root) {
        if (root) {
            let tmp = root.left;
            root.left = invertTree(root.right);
            root.right = invertTree(tmp);
        }
        return root;
    }
    

Log in to reply
 

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