I'm trying to insert a node in my binary tree. However, I don't know the proper way to do this. I understand that I should run a bfs and insert in the first null position. How do I translate that into a code?
I was trying with DFS: The tree looks like this:
class Node:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def insert(node, val):
if not node:
return Node(val)
if not node.left:
node.left = Node(val)
return
if not node.right:
node.right = Node(val)
return
return insert(node.left, val)
return insert(node.right, val)
n1, n2, n3, n4, n5, n6, n7, n8 = Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8)
n1.left, n1.right, n2.left, n2.right, n3.left, n3.right, n4.left = n2, n3, n4, n5, n6, n7, n8
But that gives me an unreachable code. What is the proper way to do this? I'm pretty frustrated by the people calling Binary Tree where they really mean BST.
n.leftandn.rightdoing? I don't think you ever declare'n'.