Hacker News new | ask | show | jobs
by emmanueloga_ 474 days ago
I think brew's author point holds even if you replace "invert binary tree" with any other LC problem.

In terms of the problem itself, a binary tree can be expressed something like:

    type Node<T> = { value: T, left?: Node<T>, right?: Node<T> }
Given a root, you can invert it recursively with some code like this:

    function invertTree(root) {
      if (!root) return null;

      // Swap!
      const tmp = root.left;
      root.left = invertTree(root.right);
      root.right = invertTree(tmp);

      return root;
    };
Or using an explicit stack:

    function invertTree(root) {
      const stack = [root];
      while (stack.length > 0) {
        const node = stack.pop(); if (!node) continue;

        // Swap!
        const tmp = node.right;
        node.right = node.left;
        node.left = tmp;

        stack.push(node.left);
        stack.push(node.right);
      }
      return root;
    }
I think without prep would be harder to come up with the non-recursive version.