Skip to content

Commit

Permalink
feat(trees): height of tree
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianLusina committed Jul 16, 2024
1 parent 0764a27 commit 803bc85
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 24 deletions.
26 changes: 7 additions & 19 deletions datastructures/trees/binary/tree/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,15 @@ def height(self) -> int:
if self.root.left is None and self.root.right is None:
return 1

height = 0
queue = FifoQueue()
queue.enqueue(self.root)
def height_helper(current_node: BinaryTreeNode) -> int:
if not current_node:
return -1
left_height = height_helper(current_node.left)
right_height = height_helper(current_node.right)

while True:
current_level_nodes = queue.size
return 1 + max(left_height, right_height)

if current_level_nodes == 0:
return height

height += 1

while current_level_nodes > 0:
node = queue.dequeue()

if node.left is not None:
queue.enqueue(node.left)

if node.right is not None:
queue.enqueue(node.right)
current_level_nodes -= 1
return height_helper(self.root)

def has_next(self) -> bool:
pass
Expand Down
22 changes: 17 additions & 5 deletions datastructures/trees/binary/tree/test_binary_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,15 +220,14 @@ def test_returns_1_for_root_but_no_children(self):
def test_returns_3_for_tree_3_9_20_null_null_15_7(self):
"""should return 3 if the binary tree [3,9,20,null,null,15,7]"""
left = BinaryTreeNode(data=9)
right_left = BinaryTreeNode(data=15)
right_right = BinaryTreeNode(data=7)
right = BinaryTreeNode(data=20, left=right_left, right=right_right)
right = BinaryTreeNode(data=20, left=BinaryTreeNode(data=15), right=BinaryTreeNode(data=7))

root = BinaryTreeNode(data=3, left=left, right=right)
tree = BinaryTree(root=root)

actual = tree.height()
self.assertEqual(3, actual)
expected = 2
self.assertEqual(expected, actual)

def test_returns_2_for_tree_1_null_20(self):
"""should return 2 if the binary tree [1,null,20]"""
Expand All @@ -238,7 +237,20 @@ def test_returns_2_for_tree_1_null_20(self):
tree = BinaryTree(root=root)

actual = tree.height()
self.assertEqual(2, actual)
expected = 1
self.assertEqual(expected, actual)

def test_returns_2_for_tree_1_2_3_4_5(self):
"""should return 2 if the binary tree [1,2,3,4,5]"""
right = BinaryTreeNode(data=3)
left = BinaryTreeNode(data=2, left=BinaryTreeNode(data=4), right=BinaryTreeNode(5))

root = BinaryTreeNode(data=1, left=left, right=right)
tree = BinaryTree(root=root)

actual = tree.height()
expected = 2
self.assertEqual(expected, actual)


class BinaryTreeLeafSimilarTest(unittest.TestCase):
Expand Down

0 comments on commit 803bc85

Please sign in to comment.