-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1758 from DhananjayPorwal/patch-1
Create Binary Tree.py
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
36 changes: 36 additions & 0 deletions
36
Program's_Contributed_By_Contributors/Python_Programs/Binary Tree.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
class Node: | ||
def __init__(self, data): | ||
self.left = None | ||
self.right = None | ||
self.data = data | ||
|
||
def insert(self, data): | ||
# Compare the new value with the parent node | ||
if self.data: | ||
if data < self.data: | ||
if self.left is None: | ||
self.left = Node(data) | ||
else: | ||
self.left.insert(data) | ||
elif data > self.data: | ||
if self.right is None: | ||
self.right = Node(data) | ||
else: | ||
self.right.insert(data) | ||
else: | ||
self.data = data | ||
|
||
# Print the tree | ||
def PrintTree(self): | ||
if self.left: | ||
self.left.PrintTree() | ||
print( self.data), | ||
if self.right: | ||
self.right.PrintTree() | ||
|
||
# Use the insert method to add nodes | ||
root = Node(12) | ||
root.insert(6) | ||
root.insert(14) | ||
root.insert(3) | ||
root.PrintTree() |