Graph
: A collection of nodes and any edges between those nodes. (Linked Lists and Trees are both considered subclasses of graphs)Tree
: Graph that does not contain any cycles.
rooted
”, or a tree where there exists a node that is accessible from every other node.Binary Tree
: Tree where nodes have at most 2 children.class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
Basic Tree Terminology
Tree
: Graph with no cycles.
Binary Tree
: Tree where nodes have at most 2 nodes.Root
: The ultimate parent, the single node s tree that can access every other node through edges; root does not have a parent.Internal Node
: Node that has children.Leaf
: Node that does not have any children.Path
: A series of nodes that can be traveled through edges.Traversing Trees
Breadth First
: Traversing level by level, visiting every node at each stage.Depth-First
:Pre-Order Traversal
:
In-Order Traversal
:
Post-Order Traversal
:
Binary Search Trees
function inOrderPrint(root) {
if (!root) return;
inOrderPrint(root.left);
console.log(root.val);
inOrderPrint(root.right);
}
// BST 1: 42
// BST 2: 4, 5, 6
// BST 3: 1, 5, 7, 10, 16, 16