Trees Pattern Flashcards

1
Q

What exactly is a tree?

A

It’s a connected DAG with a single root where each child has only a single parent.

Alternatively you can say It’s a connected DAG with a single root where the corresponding undirected graph is also acyclic.

A tree has these node types:
Root: Only outgoing
Internal nodes: have both incoming and outgoing edges
Leaves: Only incoming

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a binary tree?

A

Tree that
- each node has 0-2 children

  • height of binary tree is h nodes
  • h can at most be n which happens when the tree is really a linked list. In which case, maybe you should use a simpler data structure like a linked list.

What is the min value of h?
It happens in a perfect/complete tree

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are some indications that I should use a tree for a given problem?

A
  • If the data is hierarchical
  • The problem is recursive. In which case, we will have a recursion tree.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you solve a tree problem?

A

We use recursion

We solve the problem on the left

We solve the problem on the right

We combine the result of the left and right and the root.

Traversing the tree:
DFS
- inorder or preorder traversal

PostOrder: very common for recursive solutions on trees

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do we store the tree in code?

A

Create a node class

class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How are BST or trees stored?

A

In node class or classes

Vectors or arrays

How well did you know this?
1
Not at all
2
3
4
5
Perfectly