Skip to content

Instantly share code, notes, and snippets.

@grevych
Last active August 28, 2019 22:32
Show Gist options
  • Save grevych/b0154dd57d5c6514686797336c9ec8c4 to your computer and use it in GitHub Desktop.
Save grevych/b0154dd57d5c6514686797336c9ec8c4 to your computer and use it in GitHub Desktop.
Build a function that returns the height of a tree
def height_dfs(root):
stack = [(root, 0)]
total_height = 0
while stack:
current_node, height = stack.pop()
total_height = max(total_height, height)
if current_node.left:
stack.append((current_node.left, height + 1))
if current_node.right:
stack.append((current_node.right, height + 1))
return total_height
def height_bfs(root):
queue = [(root, 0)]
index = 0
total_height = 0
while index < len(queue):
current_node, height = queue[index]
total_height = max(total_height, height)
if current_node.left:
queue.append((current_node.left, height + 1))
if current_node.right:
queue.append((current_node.right, height + 1))
index += 1
return total_height
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment