DEV Community

Edwin
Edwin

Posted on

3 2

Inverting A Binary Tree in JavaScript and Python

Famously the creator of Homebrew failed a google interview because he failed to invert a binary tree on a whiteboard. Let's go through implementing it. Inverting a binary tree involves switching non-leaf nodes on the left side with the ones on the Right.
The image below shows a brief representation of the process.
Invert tree.

The steps to follow:-

  1. store the left property to the node
  2. set the left property to the right property of the node 3 set the right property to the stored left property
  3. recursively call InvertBinary on the left property of the node then on the right property of the node.
  4. return the tree.

Code implementation in JavaScript:-

class Node{
    constructor(val){
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

class BST{
    constructor(){
        this.root = null;
    }

    insert(val){
        let newNode = new Node(val);
        if(!this.root){
            this.root = newNode;
        }else{
            let current = this.root;
            while(true){
                if(val < current.val){
                    if(current.left === null){
                        current.left = newNode;
                        return this
                    }else{
                        current = current.left;
                    }
                }else{
                    if(current.right === null){
                        current.right = newNode;
                        return this
                    }else{
                        current = current.right
                    }
                }
            }

        }

    }

       DFSInOrder(){
        let data=[];
        function traverse(node){
            if(node.left) traverse(node.left);
            data.push(node.val);
            if(node.right) traverse(node.right);
        }
        traverse(this.root);
        return data;

    }

    IBT(){
        function Invert(node){
            if(node === null) return ;
            let temp = node.left;
            node.left = node.right;
            node.right = temp;

            Invert(node.left);
            Invert(node.right);
        }
        Invert(this.root)
        return this.DFSInOrder()
    }



}

let tree = new BST();
tree.insert(100);
tree.insert(200);
tree.insert(150);
tree.insert(80);
tree.insert(90);
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(180);
tree.insert(190);
tree.DFSInOrder();
tree.IBT();
Enter fullscreen mode Exit fullscreen mode

in Python:-

class Node:
    def __init__(self,val):
        self.val = val
        self.left = None
        self.right = None


class BST:
    def __init__(self):
        self.root= None

    def insert(self, val):
         newNode = Node(val)
         if self.root == None:
             self.root= newNode
         else:
             current = self.root
             while True:
                 if val< current.val:
                     if current.left == None:
                         current.left = newNode
                         return self
                     else:
                         current= current.left 
                 else:
                     if(current.right == None):
                         current.right = newNode
                         return self
                     else:
                         current = current.right


    def dfsInorder(self):
        data =[]

        def traverse(node):
            if(node.left): traverse(node.left)
            data.append(node.val)
            if(node.right): traverse(node.right)
        traverse(self.root)         
        return data




    def IBT(self):
        def InvertTree(node):
            if node == None: return 

            temp= node.left
            node.left = node.right
            node.right = temp

            InvertTree(node.left)
            InvertTree(node.right)
        InvertTree(self.root) 

        return self.dfsInorder()

bst = BST()
bst.insert(100)
bst.insert(200)
bst.insert(150)
bst.insert(175)
bst.insert(160)
bst.insert(180)
bst.insert(75)
bst.insert(50)
bst.insert(65)
bst.insert(40)
bst.insert(55)
bst.insert(20)

print(bst.dfsInorder())
print(bst.IBT())

Enter fullscreen mode Exit fullscreen mode

Have a nice weekend.

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

Jetbrains Survey

Calling all developers!

Participate in the Developer Ecosystem Survey 2025 and get the chance to win a MacBook Pro, an iPhone 16, or other exciting prizes. Contribute to our research on the development landscape.

Take the survey

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️