Insertion in a Binary tree Flashcards

Leetcode binary tree problems

1
Q

Insertion in a Binary tree

A

from collections import deque
class Node:
def__init__(self,d):
self.data = d
self.left = None
self.right = None
def insert(root, key):
if root is None:
return Node(key)
#function to insert a new node in the binary tree
def insert(root, key):
if root is None:
return Node(key)
queue = deque([root])

while queue:
temp = queue.popleft()

     if temp.left is None:
        temp.left = Node(key)
        break
     else:
         queue.append(temp.left)
     if temp.right is None:
        temp.right = Node(key)
        break
     else:
         queue.append(temp.right) return root

def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end = ‘ ‘)
inorder(root.right)

if __name__ == “main”:
root = Node(2)
root.left = Node(3)
root.right = Node(4)
root.left.left = Node(5)

print(“In order traversal before insertion:”, end = “ “)
inorder(root)
print()

key = 6
root = insert(root, key)

print(“in order traversal after insertion :”, end = “ “)
print()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly