Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I invert a binary tree in JavaScript?

how can i flip over binary tree? I recently came across this problem, and all my attempts to do it adequately failed. initial tree shown below.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

     4
   /   \
  7     2
 / \   / \
9   6 3   1
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
    
};
like image 830
Bogdan Zaitsev Avatar asked Sep 12 '25 11:09

Bogdan Zaitsev


1 Answers

It will be easier with recursive method in js using DFS (depth first search) and simply swap the nodes

    const trav = (currNode) => {
      if (currNode === null) {
        return;
      }
      const temp = currNode.lNode;
      currNode.lNode = currNode.rNode;
      currNode.rNode = temp;
      trav(currNode.lNode);
      trav(currNode.rNode);
    };
    trav(root);
    return root;

For more refer to the class I wrote for more interesting methods -
Class - https://www.npmjs.com/package/@dsinjs/binary-tree
Documentation for reverse() method - https://dsinjs.github.io/binary-tree/#reverse

like image 179
Siddhesh Kulkarni Avatar answered Sep 15 '25 01:09

Siddhesh Kulkarni