Binary Tree Traversal Cheat Sheet

Binary Tree Traversal Cheat Sheet

Example

Pre-Order Traversal

def preOrderHelper(tree, array = []):
if tree != None:
array.append(tree.value)
preOrderHelper(tree.left,array)
preOrderHelper(tree.right,array)
return array

In-Order Traversal

def inOrder(tree, array = []):
if tree != None:
inOrderHelper(tree.left,array)
array.append(tree.value)
inOrderHelper(tree.right,array)
return array

Post-Order Traversal

def postOrder(tree, array = []):
if tree != None:
postOrderHelper(tree.left,array)
postOrderHelper(tree.right,array)
array.append(tree.value)

Level Order Traversal

def levelOrder(root: TreeNode) -> List[List[int]]:
if root == None:
return [[]]
acc = [[]]
helper(root,acc,0)
return acc

def helper(root,acc,ind):
if root == None:
return acc
else:
if len(acc) < ind + 1:
acc.append([])
acc[ind].append(root.val)
helper(root.left,acc,ind + 1)
helper(root.right,acc,ind + 1)
return acc

--

--

--

Computer Scientist Blog: www.pranav.ai Website: www.prandev.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What Are The Best & Popular Python Frameworks

When Strings get Word-y

Languages as Libraries

Basic Scrabble Word Search

Day 24 (week 5) — Middleware and Sessions

Corner 04: Tips & Tricks

$LOKA — WORLD PREMIER

How to Host and Deploy an Angular App on Firebase

2 logos of Angular and Firebase

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pranav Ahluwalia

Pranav Ahluwalia

Computer Scientist Blog: www.pranav.ai Website: www.prandev.com

More from Medium

Pyhton developer interview experience at Renewbuy.com

Building a Twitter clone-Part 1(setup)

Publish a Free App to Heroku

Python Algorithms Every Programmer Should Know — Part 1