A binary tree is a tree where each node has at most two children. Terms: root, leaf, parent, child, height, depth, level.
- Full — every node has 0 or 2 children.
- Complete — all levels full except possibly the last, filled from the left.
- Perfect — all internal nodes have 2 children and all leaves are at the same level (2h+1 − 1 nodes).
- Balanced — height is O(log n), e.g. AVL, Red-Black tree.
struct Node {
int val;
Node *left, *right;
Node(int v) : val(v), left(nullptr), right(nullptr) {}
};
void inorder(Node *r) { if (!r) return; inorder(r->left); cout << r->val << " "; inorder(r->right); } // L N R
void preorder(Node *r) { if (!r) return; cout << r->val << " "; preorder(r->left); preorder(r->right); } // N L R
void postorder(Node *r) { if (!r) return; postorder(r->left); postorder(r->right); cout << r->val << " "; } // L R N
int height(Node *r) { return r ? 1 + max(height(r->left), height(r->right)) : 0; }
void levelOrder(Node *root) { // BFS
queue<Node*> q;
if (root) q.push(root);
while (!q.empty()) {
Node *cur = q.front(); q.pop();
cout << cur->val << " ";
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}