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

Development Snapshot: 20 October 2021

Tip of the Day: Modular AI Waypoint System in Unity3D

How to integrate eBay API with Laravel 6.x

Image  of  ebay  integration

Web Server with Live Updates Roll Out using Jenkins and K8s

Bridgefy TwitterForwarder for iOS: An app to share Tweets offline

#Monopolonph will officially introduce the unique first edition of #NFT on May 1st, 2022!

Convert Wikipedia Articles into Mind Maps

Abstraxo’s Auto generated mind map from Wikipedia’s article on dolphins

MVC Part V… Creating View in MVC

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

LeetCode Patterns Adventure 19 — Peak Index in a Mountain Array

Leetcode — Construct K Palindrome Strings

2D Array DS Hackerrank solution in Python

Coding Algorithms: Bubble Sort

A visual representation of bubble sort.