Binary tree



A binary tree is a hierarchical data structure.
 * Root: Each non-empty binary tree has exactly one root node.
 * Child nodes: Each node has a left and a right child node.
 * Leaf node: A node whose left and right children are both null is a leaf node.

Tree traversal orders
There are basically three orders to fully traverse a binary tree:

Example
10              ........root /   \         /      \        5        15       / \      /  \      2   7   12    20


 * Pre-order
 * 10 → 5 → 2 → 7 → 15 → 12 → 20


 * In-order
 * 2 → 5 → 7 → 10 → 12 → 15 → 20
 * Note that if we are doing this on a binary search tree, then the elements will appear in a strictly increasing order.


 * Post-order
 * 2 → 7 → 5 → 10 → 12 → 20 → 15

Full binary tree


A full binary tree is a binary tree such that every node in it has either 0 or 2 children.

Or we can use a recursive definition:
 * 1) A binary tree with only the root node is a full binary tree. (base case)
 * 2) * Note: an empty tree does NOT count.
 * 3) A binary tree is a full binary tree if for every node, its left subtree is a full binary tree, and its right subtree is a binary tree.

Note: A full binary tree is not necessarily a complete binary tree, or even a balanced binary tree.

Balanced binary tree


A balanced binary tree is a binary tree such that for every node in this tree, the left subtree's height and the right subtree's height differ by no more than 1.

Complete binary tree


A complete binary tree is a binary tree such that:
 * 1) All levels except the last level are filled up.
 * 2) All nodes are as far left as possible.

Note: A complete binary tree must be a balanced binary tree.

A complete binary tree with n nodes has height $$h = \lfloor \log_{2}(n) \rfloor$$.

Perfect binary tree


A perfect binary tree is a binary tree such that all nodes except the leaf nodes have exactly two children.

A perfect binary tree tree with h must have exactly $$n = 2^{h+1} - 1$$ nodes.


 * Notes
 * A perfect binary tree must be a complete binary tree. Hence it is also a balanced binary tree.
 * A perfect binary tree is also a full binary tree.

Binary search tree


A binary search tree is a binary tree such that:
 * 1) There are no duplicate values.
 * 2) For each node:
 * 3) * All values in the left subtree of this node are less than this node's value.
 * 4) * All values in the right subtree of this node are greater than this node's value.

Note: It is not required that the binary search tree is balanced. But a balanced binary tree can effectively reduce the time complexity in performing a binary tree search.