Create a binary tree in Python
To create a binary tree in Python, you can use the following code:
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, val):
if not self.root:
self.root = Node(val)
else:
cur = self.root
while True:
if val < cur.val:
if not cur.left:
cur.left = Node(val)
break
else:
cur = cur.left
else:
if not cur.right:
cur.right = Node(val)
break
else:
cur = cur.right
This code defines a Node
class that represents a node in a binary tree. Each node has a value and left and right child nodes.
The BinaryTree
class defines a binary tree. It has a root
property that represents the root node of the tree, and an insert()
method that allows you to insert new nodes into the tree.
To use this code, you can create a BinaryTree
object and then call the insert()
method to add nodes to the tree. For example:
tree = BinaryTree()
tree.insert(5)
tree.insert(3)
tree.insert(7)
This will create a binary tree with a root node that has the value 5, and left and right child nodes with the values 3 and 7, respectively.
One Response to Create a binary tree in Python