Binary Tree¶
Binary trees are a fundamental data structure in computer science, where each node has at most two children, referred to as the left and right child. They are used in various applications such as searching, sorting, and representing hierarchical data.
- Pre Order Traversal (DFS): Visit the root node first, then recursively visit the left subtree, followed by the right subtree.
- In Order Traversal (DFS): Recursively visit the left subtree first, then visit the root node, followed by the right subtree.
- Level Order Traversal (BFS): Visit nodes level by level, starting from the root and moving down to the leaves.
Import packages
Define node class
Defining tree
graph TD
A[1]
B[2]
C[3]
D[4]
E[5]
F[10]
A --> B
A --> C
B --> D
B --> E
C --> F
Recursive pre order traversal DFS (Depth First Search)
- Time complexity: O(n) - Each node is visited once.
- Space complexity: O(n) - In the worst case (a completely unbalanced tree).
Recursive in order traversal DFS (Depth First Search)
- Time complexity: O(n) - Each node is visited once.
- Space complexity: O(n) - In the worst case (a completely unbalanced tree).
Interactive pre order traversal DFS (Depth First Search)
- Time complexity: O(n) - Each node is visited once.
- Space complexity: O(n) - In the worst case (a completely unbalanced tree).
Level order traversal BFS (Breadth First Search)
- Time complexity: O(n) - Each node is visited once.
- Space complexity: O(n) - In the worst case (a completely unbalanced tree).
Check if value exists DFS (Depth First Search)
- Time complexity: O(n) - Each node is visited once.
- Space complexity: O(n) - In the worst case (a completely unbalanced tree).