Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 74b277d

Browse files
Merge pull request fnplus#481 from SubCoder1/master
added height of tree bst implementation python
2 parents 885c4b3 + eaa2eed commit 74b277d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Node:
2+
def __init__(self, value):
3+
self.value = value
4+
self.left, self.right = None, None
5+
6+
def get_left_child(self):
7+
return self.left
8+
9+
def get_right_child(self):
10+
return self.right
11+
12+
class BinarySearchTree:
13+
def __init__(self):
14+
self.root = None
15+
16+
def insert_into_tree(self, value):
17+
newNode = Node(value=value)
18+
if self.root is None:
19+
self.root = newNode
20+
else:
21+
root = self.root
22+
while root:
23+
if value < root.value:
24+
if root.left is None:
25+
root.left = newNode
26+
break
27+
else:
28+
root = root.left
29+
else:
30+
if root.right is None:
31+
root.right = newNode
32+
break
33+
else:
34+
root = root.right
35+
36+
def height_of_tree(self, root):
37+
if root is None:
38+
return 0
39+
else:
40+
l_subtree_height = self.height_of_tree(root.left)
41+
r_subtree_height = self.height_of_tree(root.right)
42+
43+
return max(l_subtree_height, r_subtree_height) + 1
44+
45+
if __name__ == '__main__':
46+
# Initializing a Binary Search Tree
47+
BST = BinarySearchTree()
48+
# Inserting into the tree in a BST fashion
49+
BST.insert_into_tree(value=190)
50+
BST.insert_into_tree(value=14)
51+
BST.insert_into_tree(value=199)
52+
BST.insert_into_tree(value=3)
53+
BST.insert_into_tree(value=25)
54+
55+
# Calculating & printing the height of tree
56+
print(BST.height_of_tree(root=BST.root))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /