1 of 21

Trees

By: Johnny Lu

2 of 21

Sign in here!

https://linktr.ee/bingacm

3 of 21

What are trees?

  • Nonlinear data structure

  • Collection of nodes connected by edges

  • Data stored in nodes

4 of 21

Some Types of Trees

01

02

03

AVL Trees

Huffman Tree

Red-Black Trees

5 of 21

Binary Tree

  • Each node has at most 2 children

Terminology

  • Root, Node, Edge, Leaf
  • Parent, Child

6 of 21

Root

Leaf

Edge

7 of 21

Root of this left subtree = 2

Root of this right subtree = 3

8 of 21

Binary Search Tree

9 of 21

Tree Traversals

How do we access the values stored in trees?

Algorithms that let us visit all the nodes in a tree

2

1

3

10 of 21

Recursion

A function that calls itself (recursive function)

#recursive function that finds the sum of first n natural numbers

def recursiveSum(n):

if n <= 0:

return n

return n + recursiveSum(n-1)

Example:

n=3 has output of 6

11 of 21

Depth First Search (DFS)

Typically done recursively

  • Preorder Traversal - (Root, Left, Right) -> (1, 2, 5, 6, 3)
  • Inorder Traversal - (Left, Root, Right) -> (5, 2, 6, 1, 3)
  • Postorder Traversal - (Left, Right, Root) -> (2, 5, 6, 3, 1)

Visits lowest depth of tree first

12 of 21

Breadth First Search (BFS)

Typically done using a queue as opposed to recursion

Visits all of a node’s children before visiting their children

[[1], [2, 3], [5, 6]]

13 of 21

Tree Methods

14 of 21

Given the root of a binary tree, return the preorder traversal of its nodes' values.

144 - Binary Tree Preorder Traversal

15 of 21

Python

Java

16 of 21

Inorder

Preorder

Postorder

17 of 21

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

104 - Maximum Depth of Binary Tree

18 of 21

Python

Java

19 of 21

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

102 - Binary Tree Level Order Traversal

20 of 21

Python

21 of 21

Thank you for coming!