Two Strategies to traverse a binary tree
1. Breadth First Search (BFS)
Scan through the tree level by level, following the order of height, from top to bottom. The nodes on the higher level would be visited before the ones on the lower levels.
2. Depth First Search (DFS)
Depth has priority in this strategy so that the search would start from a root and reach all the way down to a certain leaf, and then back to the root to reach another branch.
DFS can further be distinguished as preorder, inorder and postorder depends on the relative order among the root node, left node and right node.
Leetcode Problems
1. Binary Tree Preorder Traversal (Leetcode Number: 144)
node -> left -> right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
# Create stack to store the node and respective child nodes separately
stack, res = [root], []
# Put the left nodes at the end of stack as the pop() function extract last element first
while stack:
root = stack.pop()
if root is not None:
res.append(root.val)
if root.right is not None:
stack.append(root.right)
if root.left is not None:
stack.append(root.left)
return res
2. Binary Tree Postorder Traversal (Leetcode Number: 145)
left -> right -> node
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def posterorder(root):
if root is None:
return
posterorder(root.left)
posterorder(root.right)
res.append(root.val)
posterorder(root)
return res
3. Binary Tree Inorder Traversal (Leetcode Number: 94)
left -> node -> right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def inorder(root):
if root is None:
return
inorder(root.left)
res.append(root.val)
inorder(root.right)
inorder(root)
return res