nathanwailes

Binary tree - Get height

Jun 10th, 2024
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.73 KB | None | 0 0
  1. """
  2. """
  3. class TreeNode:
  4.     def __init__(self, value=0, left=None, right=None):
  5.         self.value = value
  6.         self.left = left
  7.         self.right = right
  8.  
  9. def height(node):
  10.     if node is None:
  11.         return -1  # if using 0-based height (0 for single node, -1 for empty tree)
  12.    
  13.     left_height = height(node.left)
  14.     right_height = height(node.right)
  15.    
  16.     return max(left_height, right_height) + 1
  17.  
  18. # Example usage:
  19. # Constructing a simple binary tree
  20. #         1
  21. #        / \
  22. #       2   3
  23. #      / \
  24. #     4   5
  25.  
  26. root = TreeNode(1)
  27. root.left = TreeNode(2)
  28. root.right = TreeNode(3)
  29. root.left.left = TreeNode(4)
  30. root.left.right = TreeNode(5)
  31.  
  32. print("Height of the tree:", height(root))  # Output: 2
  33.  
Advertisement
Add Comment
Please, Sign In to add comment