Coding Towards The Answer, Part 11
Traversing The Tree …
8 min readOct 18, 2023
3 main methods for Tree Traversal using DFS (Depth-First Search / Traversal):
In order Traversal (left, root, right)
Preorder Traversal (root, left, right)
Postorder Traversal (left, right, root)
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorderTraversal(root):
answer = []
inorderTraversalUtil(root, answer)
return answer
def inorderTraversalUtil(root, answer):
if root is None:
return
inorderTraversalUtil(root.left, answer)
answer.append(root.val)
inorderTraversalUtil(root.right, answer)
return
def preorderTraversal(root):
answer = []
preorderTraversalUtil(root, answer)
return answer
def preorderTraversalUtil(root, answer):
if root is None:
return
answer.append(root.val)
preorderTraversalUtil(root.left, answer)
preorderTraversalUtil(root.right, answer)
return
def postorderTraversal(root):
answer = []
postorderTraversalUtil(root, answer)
return answer
def…