Trees and Graphs
Traversals for Binary Trees
1. Preorder - Node is operated on first, then the left child, followed by the right child. 2. Inorder - Left node is operated on first, then the main node, then the right child node. 3. Postorder - Left node is operated on first, then the right child node, and finally the main node last.
Graphs
Consist of nodes with children but unlike tree nodes, graph nodes can have multiple parents, possibly creating a loop (a cycle). - More complex than trees. - Link between nodes may contain Edges (contain more than just a pointer).
Directed Graph
A graph with one-way edges.
Undirected Graph
A graph with only two-way pointers.
Descendant
All the nodes that can be reached by following a path of child nodes from a particular node are the descendants of that node.
Ancestor
An ancestor of a node is any other node from which the node is a descendant.
BST
Binary Search Tree. The value held by the left child is less than or equal to its own value, and the value held by a node's right child is greater than or equal to its value. - O(log n) lookup time.
Binary Tree
Each node has no more than two children, referred to as left and right.
Depth-First Search
Follows one branch of the tree down as many levels as possible until the target node is found or the end is reached. When the search can't go any further, it is continued at the nearest ancestor with unexplored children. - No need to store child nodes. - Better if the node is likely to be at the bottom of the tree.
Tree
Made up of nodes (data elements) with zero, one, or several references (or pointers) to other nodes. Each node has only one other node referencing it.
Breadth-First Search
Start with the root, move left to right across the second level, then move left to right across the third level, and so forth. Continue until you've examined all of the nodes or you find the node you're searching for. - Uses additional memory to track the child nodes for all nodes on a given level while searching that level. - Better if the node is likely to be at the top of the tree.
Find the Height of a Binary Tree
The function is recursively called for each child of each node, so the function will be called once for each node in the tree. - Runtime is O(n)
Leaves
The leaves are nodes that do not have any children.
Root
The node from which you have a path to every other node.
Child
A node is the child of any node that points to it.
Parent
A node that points to other nodes is the parent of those nodes. Every node except the root has a parent.
Heap
Trees (usually binary trees) where each child of a node has a value less than or equal to the node's own value. - The root node always has the largest value in the tree. - If extracting the max value needs to be fast