# Trees, Binary Trees & Tree Traversals in C++: Complete Beginner's Guide

> Binary tree in C++: terminology, full vs complete vs perfect trees, building a tree, and inorder, preorder, postorder and level order traversal.

- Canonical URL: https://shafinchowdhury.dev/posts/tree-binary-tree-traversals/
- Author: Shafin Chowdhury (https://shafinchowdhury.dev/about/)
- Published: 2026-12-04T03:00:00.000Z
- Updated: 2026-12-04T03:00:00.000Z
- Reading Time: 19 min read
- Tags: cpp, data-structures, trees, binary-tree, beginners

---

import Diagram from "@/components/Diagram.astro";
import TraversalPlayer from "@/components/TraversalPlayer.astro";

A **tree** is a data structure that stores items in a hierarchy: one node at the top (the root), and every other node hangs below exactly one parent. A **binary tree** is a tree where each node has at most two children, called left and right. **Tree traversal** means visiting every node once in a fixed order: inorder (Left, Root, Right), preorder (Root, Left, Right), postorder (Left, Right, Root), or level order (top to bottom). Each traversal runs in $O(n)$ time.

This guide builds everything from scratch in C++: the vocabulary, the different kinds of binary tree, how to create a tree from code and from input, and all four traversals traced step by step on **one example tree**, so you can compare their outputs side by side.

> **Tree & Graph series, step 1 of 8.** Next: [Binary Search Tree (BST) in C++](/posts/binary-search-tree-bst/). Full series on the [Trees & Graphs topic page](/topics/trees-graphs/).

---

## What Is a Tree in Data Structures?

Arrays, [stacks](/posts/understanding-stack-in-cpp/) and [queues](/posts/understanding-queue-in-cpp/) are **linear**: each element has at most one element before it and one after it. A tree is **non-linear** and **hierarchical**: one element can have many elements below it.

Formally, a tree is a set of **nodes** connected by **edges** such that:

1. There is exactly one special node called the **root**.
2. Every node except the root has exactly **one parent**.
3. There are **no cycles**: from the root there is exactly one path to any node.

A tree with $n$ nodes always has exactly $n - 1$ edges, because every node except the root has one edge going up to its parent.

## What Is a Tree Node?

A **node** is the building block of a tree: one object that stores a value and links to its children. In this article every tree is a **binary tree** (each node has at most two children, called left and right; defined properly [below](#what-is-a-binary-tree)), so a node in C++ looks like this:

```cpp excerpt
struct Node {
    int data;
    Node* left;
    Node* right;

    explicit Node(int value) : data(value), left(nullptr), right(nullptr) {}
};
```

- `data` holds the value (an `int` here; it could be a `string` or any type).
- `left` points to the root of the left subtree, or `nullptr` if there is none.
- `right` points to the root of the right subtree, or `nullptr` if there is none.

The constructor sets both pointers to `nullptr`, so a freshly created node is a leaf. Forgetting to initialise these pointers is one of the most common beginner bugs, because an uninitialised pointer holds garbage and your traversal will crash when it follows it.

A tree is then simply a pointer to its root node: `Node* root`. An **empty tree** is `root == nullptr`. (A node in a general tree, where any number of children is allowed, would store a list such as `vector<Node*> children` instead of `left` and `right`.)

## Tree Terminology

Every term below is marked on the diagram.

<Diagram
  src="tree-binary-tree-traversals/tree-terminology"
  alt="A general tree with root A. A has children B, C and D. B has children E and F. D has children G and H, and H has child I. Labels mark the root, an edge, a parent, siblings, leaves, an internal node, a subtree and the depth of I."
/>

| Term | Meaning | In the diagram |
| --- | --- | --- |
| **Root** | The only node with no parent | A |
| **Parent** | A node directly above another node | B is the parent of E and F |
| **Child** | A node directly below another node | E and F are children of B |
| **Sibling** | Nodes with the same parent | E and F; also B, C and D |
| **Leaf (external node)** | A node with no children | C, E, F, G, I |
| **Internal node** | A node with at least one child | A, B, D, H |
| **Edge** | The link between a parent and a child | A–B |
| **Path** | A sequence of nodes joined by edges | A → D → H → I |
| **Depth of a node** | Number of edges from the root down to that node | depth(A) = 0, depth(I) = 3 |
| **Height of a node** | Number of edges on the longest path from that node down to a leaf | height(D) = 2, height(I) = 0 |
| **Height of the tree** | Height of the root | 3 |
| **Level** | All nodes at the same depth | level 1 = B, C, D |
| **Subtree** | A node together with all of its descendants | the box around D, G, H, I |
| **Degree of a node** | Number of children of that node | degree(A) = 3, degree(D) = 2 |
| **Degree of a tree** | The largest degree of any node | 3 |

> **Depth vs height, the one-line version:** depth is measured **from the root down** to a node; height is measured **from a node down** to its deepest leaf. The root has depth 0; every leaf has height 0.

**Watch out for conventions.** Most textbooks and this site count height in **edges**, so a single node has height 0 and an empty tree has height −1. Some courses and LeetCode's "maximum depth" count **nodes** instead, so a single node has height 1. Both are fine; just state which one you use in an exam answer.

## Real-World Applications of Trees

You use trees every day, usually without noticing:

| Where | What the tree stores |
| --- | --- |
| File systems | Folders contain files and sub-folders |
| HTML / the DOM | `<html>` contains `<body>`, which contains `<div>`s |
| Compilers | Expressions become **expression trees** / syntax trees |
| Databases | B-trees and B+ trees index millions of rows |
| `std::map`, `std::set` | Usually a red-black tree (a self-balancing BST) |
| Priority queues | A binary heap, which is a complete binary tree stored in an array |
| Networking | Routing tables, spanning trees |
| AI and games | Decision trees, game trees (minimax) |
| Compression | Huffman coding trees |

## What Is a Binary Tree?

A **binary tree** is a tree in which every node has **at most two children**, and the two child positions are distinguished: the **left child** and the **right child**. A node with only a right child is a different tree from a node with only a left child.

Here is the binary tree used for every example in this article:

<Diagram
  src="tree-binary-tree-traversals/binary-tree-structure"
  alt="Binary tree with root 1. Node 1 has left child 2 and right child 3. Node 2 has left child 4 and right child 5. Node 5 has left child 7. Node 3 has only a right child, 6. Missing children are shown as nullptr."
/>

- 1 is the root.
- 2 is the left child of 1, and 3 is the right child of 1.
- 3 has **no left child** (`nullptr`) and a right child, 6.
- 5 has a left child, 7, and **no right child**.
- Leaves: 4, 7 and 6. Height: 3 (path 1 → 2 → 5 → 7).

### Useful binary tree properties

For a binary tree with height $h$ (in edges) and $n$ nodes:

- Level $i$ has at most $2^i$ nodes (level 0 has 1, level 1 has 2, level 2 has 4, ...).
- The tree has at most $2^{h+1} - 1$ nodes.
- The minimum possible height is $\lfloor \log_2 n \rfloor$; the maximum is $n - 1$ (a chain).
- In any binary tree, if $n_0$ is the number of leaves and $n_2$ the number of nodes with two children, then $n_0 = n_2 + 1$.
- A tree with $n$ nodes has $n - 1$ edges and $n + 1$ `nullptr` child pointers.

## Types of Binary Trees

These five names are the most common source of confusion in exams and interviews, so each panel below is chosen to show a tree that is one type but **not** another.

<Diagram
  src="tree-binary-tree-traversals/binary-tree-types"
  alt="Five binary trees side by side: a full tree that is not complete, a complete tree that is not full, a perfect tree with seven nodes, a height-balanced tree that is not complete, and a right-skewed chain of four nodes."
/>

| Type | Rule | Quick test |
| --- | --- | --- |
| **Full** (proper, strict) | Every node has **0 or 2** children | No node has exactly one child |
| **Complete** | Every level is completely filled **except possibly the last**, and the last level is filled **from the left** | Level-order listing has no gap before the last node |
| **Perfect** | All internal nodes have 2 children **and** all leaves are at the same depth | Exactly $2^{h+1} - 1$ nodes |
| **Balanced** (height-balanced) | At **every** node, the heights of the left and right subtrees differ by at most 1 | Used by AVL trees |
| **Degenerate / skewed** | Every internal node has exactly **one** child | Looks like a linked list; height $n - 1$ |

How they relate:

- Every **perfect** tree is both full and complete.
- A **full** tree need not be complete (first panel: the last level is not filled from the left).
- A **complete** tree need not be full (second panel: node 3 has only one child).
- Every complete tree is balanced, but a balanced tree need not be complete (fourth panel).
- A skewed tree is the worst case: operations that should take $O(\log n)$ take $O(n)$. You will see why this matters in the [BST guide](/posts/binary-search-tree-bst/).

## Tree Representation in C++

There are two standard ways to store a binary tree.

### 1. Linked representation (nodes and pointers)

Each node is an object holding the data and two pointers, exactly the `struct Node` from [What Is a Tree Node?](#what-is-a-tree-node). This is what you will use 95% of the time.

### 2. Array representation

Store the nodes level by level in an array. With 0-based indexing, the node at index `i` has:

- left child at `2*i + 1`
- right child at `2*i + 2`
- parent at `(i - 1) / 2`

The example tree in level order with gaps is `[1, 2, 3, 4, 5, _, 6, _, _, 7]`. This is perfect for **complete** trees (that is how a binary heap is stored) but wastes space on sparse trees: a skewed tree with $n$ nodes can need about $2^n$ slots.

## How to Create a Binary Tree in C++

To build the example tree, create each node with `new` and connect it to its parent by assigning `left` or `right`:

```cpp excerpt
Node* root = new Node(1);              // the root
root->left = new Node(2);              // 1's left child
root->right = new Node(3);             // 1's right child
root->left->left = new Node(4);        // 2's left child
root->left->right = new Node(5);       // 2's right child
root->right->right = new Node(6);      // 3's RIGHT child (3 has no left child)
root->left->right->left = new Node(7); // 5's left child
```

Read each line as "go to a node, then attach a new child on one side". `root->left->right` means "the right child of the left child of the root", which is node 5.

Because every node was created with `new`, the program must `delete` them when it is done. The safe order is **postorder**: delete both children before the parent, otherwise you lose the pointers to the children.

```cpp excerpt
void destroy(Node* root) {
    if (root == nullptr) {
        return;
    }
    destroy(root->left);
    destroy(root->right);
    delete root; // children are already gone, so this is safe
}
```

## How to Build a Tree From Input

Typing pointer chains does not scale. Programs (and lab exams) usually read a tree from input. The most common format lists the tree **in level order**, using `-1` for a missing child, the same idea LeetCode uses with `null`.

The algorithm uses a [queue](/posts/understanding-queue-in-cpp/): the queue holds the nodes that are still waiting to receive their children.

1. Read the first value and make it the root. Push the root into the queue.
2. While the queue is not empty: pop a node, read two values. If the first is not `-1`, create the left child and push it. If the second is not `-1`, create the right child and push it.

```cpp
#include <iostream>
#include <queue>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
    explicit Node(int value) : data(value), left(nullptr), right(nullptr) {}
};

// Reads a tree in level order; -1 means "no child here".
Node* buildLevelOrder() {
    int value;
    if (!(cin >> value) || value == -1) {
        return nullptr;
    }

    Node* root = new Node(value);
    queue<Node*> pending; // nodes whose children have not been read yet
    pending.push(root);

    while (!pending.empty()) {
        Node* current = pending.front();
        pending.pop();

        int leftValue, rightValue;
        if (!(cin >> leftValue >> rightValue)) {
            break; // input ended early
        }

        if (leftValue != -1) {
            current->left = new Node(leftValue);
            pending.push(current->left);
        }
        if (rightValue != -1) {
            current->right = new Node(rightValue);
            pending.push(current->right);
        }
    }
    return root;
}

void inorder(Node* root) {
    if (root == nullptr) {
        return;
    }
    inorder(root->left);
    cout << root->data << ' ';
    inorder(root->right);
}

void destroy(Node* root) {
    if (root == nullptr) {
        return;
    }
    destroy(root->left);
    destroy(root->right);
    delete root;
}

int main() {
    Node* root = buildLevelOrder();
    cout << "Inorder: ";
    inorder(root);
    cout << '\n';
    destroy(root);
}
```

**Input:**

```text
1 2 3 4 5 -1 6 -1 -1 7 -1 -1 -1 -1 -1
```

**Output:**

```text
Inorder: 4 2 7 5 1 3 6
```

Count the tokens: one for the root plus two for each of the 7 nodes gives 15 values. Every real node eventually gets popped and reads exactly two values, which is why leaves are followed by `-1 -1`.

## Tree Traversal: Inorder, Preorder, Postorder and Level Order

A **traversal** visits every node exactly once. Linear structures have one natural order; a tree has several. The three **depth-first** traversals differ only in **when the root is visited** relative to its two subtrees:

| Traversal | Order | Mnemonic |
| --- | --- | --- |
| **Preorder** | Root, Left, Right | root **pre** (before) the subtrees |
| **Inorder** | Left, Root, Right | root **in** between the subtrees |
| **Postorder** | Left, Right, Root | root **post** (after) the subtrees |
| **Level order** | Level 0, then level 1, then level 2, ..., left to right | breadth-first |

The left subtree is always handled before the right subtree in all of them. All four results for our example tree:

| Traversal | Output |
| --- | --- |
| Preorder | `1 2 4 5 7 3 6` |
| Inorder | `4 2 7 5 1 3 6` |
| Postorder | `4 7 5 2 6 3 1` |
| Level order | `1 2 3 4 5 6 7` |

Use the player below to watch each traversal run. The **call stack** shows which recursive calls are active, from the outermost call on the left to the current call on the right. The dashed nodes are on the stack but not yet printed.

<TraversalPlayer
  tree={[1, 2, 3, 4, 5, null, 6, null, null, 7]}
  orders={["preorder", "inorder", "postorder", "levelorder"]}
  caption="Interactive traversal of the example binary tree. Choose a traversal, then step through it or press Play."
/>

## Inorder Traversal (Left, Root, Right)

**Rule:** traverse the left subtree, visit the root, traverse the right subtree.

<Diagram
  src="tree-binary-tree-traversals/inorder-traversal"
  alt="The example tree with a numbered badge on each node showing its position in inorder traversal: 4 first, then 2, 7, 5, 1, 3 and 6. The output row reads 4 2 7 5 1 3 6."
/>

Step by step from the root:

1. At 1: go left to 2 first. At 2: go left to 4. 4 has no left child, so **print 4**; it has no right child either, so return.
2. Back at 2: its left subtree is done, so **print 2**. Then go right to 5.
3. At 5: go left to 7. **Print 7**. Back at 5: **print 5**. 5 has no right child.
4. 2's subtree is finished. Back at 1: **print 1**, then go right to 3.
5. At 3: there is no left child, so **print 3**. Go right to 6 and **print 6**.

**Inorder: `4 2 7 5 1 3 6`**

Why it matters: on a **binary search tree**, inorder prints the keys in **sorted order**. That single fact powers many BST interview questions.

## Preorder Traversal (Root, Left, Right)

**Rule:** visit the root, traverse the left subtree, traverse the right subtree.

<Diagram
  src="tree-binary-tree-traversals/preorder-traversal"
  alt="The example tree with badges showing preorder positions: 1 first, then 2, 4, 5, 7, 3 and 6. The output row reads 1 2 4 5 7 3 6."
/>

1. **Print 1**, then go left.
2. **Print 2**, go left: **print 4** (a leaf).
3. Back at 2, go right: **print 5**, go left: **print 7**.
4. Left half of the tree is done. Back at 1, go right: **print 3**. No left child; go right: **print 6**.

**Preorder: `1 2 4 5 7 3 6`**

Why it matters: preorder records a parent before its children, so it is used to **copy** or **serialize** a tree. The first value of a preorder sequence is always the root.

## Postorder Traversal (Left, Right, Root)

**Rule:** traverse the left subtree, traverse the right subtree, visit the root.

<Diagram
  src="tree-binary-tree-traversals/postorder-traversal"
  alt="The example tree with badges showing postorder positions: 4 first, then 7, 5, 2, 6, 3 and finally the root 1. The output row reads 4 7 5 2 6 3 1."
/>

1. Go all the way left: **print 4** (no children).
2. Back at 2, its right subtree is 5. 5's left subtree is 7: **print 7**. 5 has no right child: **print 5**.
3. Both subtrees of 2 are done: **print 2**.
4. Back at 1, go right to 3. No left child; right child 6: **print 6**. Then **print 3**.
5. Finally **print 1**.

**Postorder: `4 7 5 2 6 3 1`**

Why it matters: postorder finishes the children before the parent, so it is the right order to **delete** a tree, compute **heights and sizes** (a node needs its children's answers first), and evaluate an **expression tree**. The last value is always the root.

## Level Order Traversal (Brief Introduction)

**Rule:** visit nodes level by level, left to right. Instead of recursion, level order uses a **queue**: dequeue a node, print it, enqueue its children.

<Diagram
  src="tree-binary-tree-traversals/levelorder-traversal"
  alt="The example tree with badges showing level order positions: 1, then 2 and 3, then 4, 5 and 6, then 7. The output row reads 1 2 3 4 5 6 7."
/>

| Step | Dequeue and print | Enqueue | Queue after (front → back) |
| --- | --- | --- | --- |
| start | | 1 | `[1]` |
| 1 | 1 | 2, 3 | `[2, 3]` |
| 2 | 2 | 4, 5 | `[3, 4, 5]` |
| 3 | 3 | 6 | `[4, 5, 6]` |
| 4 | 4 | | `[5, 6]` |
| 5 | 5 | 7 | `[6, 7]` |
| 6 | 6 | | `[7]` |
| 7 | 7 | | `[]` |

**Level order: `1 2 3 4 5 6 7`**

Level order is **breadth-first search (BFS)** applied to a tree, while preorder, inorder and postorder are all forms of **depth-first search (DFS)**. Both ideas get their own guide in [What Are DFS and BFS?](/posts/what-is-dfs-and-bfs/).

## Recursive Traversal Implementation in C++

Each recursive traversal has the same shape:

- **Base case:** if the node is `nullptr` (an empty subtree), there is nothing to visit, so return.
- **Recursive case:** make two recursive calls (left subtree, right subtree) and print the current node **before**, **between**, or **after** them.

That is the only difference between the three functions below. Here is a complete program that builds the example tree, runs all four traversals and computes a few basic properties:

```cpp
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
    explicit Node(int value) : data(value), left(nullptr), right(nullptr) {}
};

void preorder(Node* root) {
    if (root == nullptr) {
        return;    // base case: empty subtree
    }
    cout << root->data << ' ';      // Root
    preorder(root->left);           // Left
    preorder(root->right);          // Right
}

void inorder(Node* root) {
    if (root == nullptr) {
        return;
    }
    inorder(root->left);            // Left
    cout << root->data << ' ';      // Root
    inorder(root->right);           // Right
}

void postorder(Node* root) {
    if (root == nullptr) {
        return;
    }
    postorder(root->left);          // Left
    postorder(root->right);         // Right
    cout << root->data << ' ';      // Root
}

void levelOrder(Node* root) {
    if (root == nullptr) {
        return;
    }
    queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
        Node* current = q.front();
        q.pop();
        cout << current->data << ' ';
        if (current->left) {
            q.push(current->left);
        }
        if (current->right) {
            q.push(current->right);
        }
    }
}

// Height in edges: empty tree = -1, single node = 0.
int height(Node* root) {
    if (root == nullptr) {
        return -1;
    }
    return 1 + max(height(root->left), height(root->right));
}

int countNodes(Node* root) {
    if (root == nullptr) {
        return 0;
    }
    return 1 + countNodes(root->left) + countNodes(root->right);
}

int countLeaves(Node* root) {
    if (root == nullptr) {
        return 0;
    }
    if (root->left == nullptr && root->right == nullptr) {
        return 1;
    }
    return countLeaves(root->left) + countLeaves(root->right);
}

void destroy(Node* root) {
    if (root == nullptr) {
        return;
    }
    destroy(root->left);
    destroy(root->right);
    delete root;
}

int main() {
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->right = new Node(6);
    root->left->right->left = new Node(7);

    cout << "Preorder:    ";
    preorder(root);
    cout << '\n';
    cout << "Inorder:     ";
    inorder(root);
    cout << '\n';
    cout << "Postorder:   ";
    postorder(root);
    cout << '\n';
    cout << "Level order: ";
    levelOrder(root);
    cout << '\n';
    cout << "Height (edges): " << height(root) << '\n';
    cout << "Nodes: " << countNodes(root) << '\n';
    cout << "Leaves: " << countLeaves(root) << '\n';

    destroy(root);
}
```

**Output:**

```text
Preorder:    1 2 4 5 7 3 6
Inorder:     4 2 7 5 1 3 6
Postorder:   4 7 5 2 6 3 1
Level order: 1 2 3 4 5 6 7
Height (edges): 3
Nodes: 7
Leaves: 3
```

### How the recursion actually runs

Take `inorder(root)` on node 2's subtree. The calls nest like this (indentation = call depth):

```text
inorder(2)
  inorder(4)
    inorder(nullptr)   -> returns
    print 4
    inorder(nullptr)   -> returns
  print 2
  inorder(5)
    inorder(7)
      inorder(nullptr) -> returns
      print 7
      inorder(nullptr) -> returns
    print 5
    inorder(nullptr)   -> returns
```

Every node causes exactly one call, and every `nullptr` child causes one call that returns immediately. That is $n$ real calls plus $n + 1$ empty calls, so the work is linear.

Want the iterative versions with an explicit stack (a favourite viva question)? They are written out in the [tree exam questions guide](/posts/tree-questions-university-exams-bangladesh/).

## Time and Space Complexity

| Operation | Time | Extra space |
| --- | --- | --- |
| Preorder / inorder / postorder (recursive) | $O(n)$ | $O(h)$ call stack |
| Level order (queue) | $O(n)$ | $O(w)$, where $w$ is the widest level |
| Height, count nodes, count leaves | $O(n)$ | $O(h)$ |
| Build from level-order input | $O(n)$ | $O(w)$ queue |

Here $n$ is the number of nodes and $h$ the height. Each node is visited once, so time is $O(n)$. The space is the recursion depth: $O(\log n)$ for a balanced tree, but $O(n)$ for a skewed tree, where a deep enough chain (around a hundred thousand nodes) can overflow the call stack. For a perfect tree, the last level holds about $n/2$ nodes, so level order's queue can reach $O(n)$.

## Common Mistakes Beginners Make

1. **Missing the base case.** Without `if (root == nullptr) { return; }` the function dereferences a null pointer and crashes on the first leaf.
2. **Uninitialised child pointers.** `Node* n = new Node;` with no constructor leaves `left` and `right` as garbage. Always set them to `nullptr`.
3. **Confusing height and depth**, or mixing the edge and node conventions in one answer. Say "height in edges" explicitly.
4. **Checking only the left child for a leaf.** A leaf needs **both** `left == nullptr` and `right == nullptr`; node 3 in our tree has no left child but is not a leaf.
5. **Losing the root.** Writing `root = root->left;` while building or traversing overwrites your only handle to the tree. Use a separate `current` pointer.
6. **Deleting the parent first.** `delete root; destroy(root->left);` reads freed memory. Delete in postorder.
7. **Treating every binary tree as a BST.** Searching left/right by comparing values only works when the tree has the BST property; in a general binary tree you must search both subtrees.
8. **Assuming one traversal identifies a tree.** Different trees can share a preorder. You need inorder **plus** preorder or postorder to rebuild a tree uniquely (with distinct values).

## Practice Problems

Try them in this order; each builds on the previous one.

| # | Problem | Skill |
| --- | --- | --- |
| 1 | [Binary Tree Inorder Traversal (LeetCode 94)](https://leetcode.com/problems/binary-tree-inorder-traversal/) | Recursion template |
| 2 | [Binary Tree Preorder Traversal (LeetCode 144)](https://leetcode.com/problems/binary-tree-preorder-traversal/) | Visit before recursing |
| 3 | [Binary Tree Postorder Traversal (LeetCode 145)](https://leetcode.com/problems/binary-tree-postorder-traversal/) | Visit after recursing |
| 4 | [Binary Tree Level Order Traversal (LeetCode 102)](https://leetcode.com/problems/binary-tree-level-order-traversal/) | Queue, level by level |
| 5 | [Maximum Depth of Binary Tree (LeetCode 104)](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | Postorder-style return values |
| 6 | [Same Tree (LeetCode 100)](https://leetcode.com/problems/same-tree/) | Recursing on two trees at once |
| 7 | [Construct Binary Tree from Preorder and Inorder (LeetCode 105)](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | Using traversal properties |

Offline exercises, using the example tree from this article:

1. Without running code, write the preorder of the tree after removing node 7. (Answer: `1 2 4 5 3 6`.)
2. Add a left child 8 to node 3. What are the new inorder and level order? (Answers: `4 2 7 5 1 8 3 6` and `1 2 3 4 5 8 6 7`.)
3. Is the example tree full? Complete? Height-balanced?
   - **Not full:** nodes 3 and 5 each have exactly one child.
   - **Not complete:** in level order, the empty left slot of node 3 comes before node 6.
   - **Balanced:** check every node. At 1: left height 2, right height 1. At 2: 0 and 1. At 3: −1 and 0. At 5: 0 and −1. Every difference is at most 1, so it **is** height-balanced.

The last answer is a good reminder to check the balance condition at **every** node, not just the root.

## Frequently Asked Questions

### What is the difference between a tree and a binary tree?

A general tree lets each node have any number of children. A binary tree limits each node to at most two, and labels them left and right. Every binary tree is a tree, but not every tree is a binary tree.

### Which traversal gives sorted output?

Inorder, but **only for a binary search tree**. On an ordinary binary tree, inorder output has no special order.

### Can I rebuild a binary tree from one traversal?

Not in general. Preorder alone, for example, cannot tell whether the second node is a left or a right child. Inorder together with preorder (or with postorder) rebuilds a tree with distinct values uniquely. Preorder plus postorder is enough only for full binary trees.

### Is level order traversal DFS or BFS?

BFS. Preorder, inorder and postorder are DFS.

## Next Steps

You now know how a binary tree is stored and walked. Continue the series:

1. **Next:** [Binary Search Tree (BST) in C++](/posts/binary-search-tree-bst/): add an ordering rule and get fast search, insert and delete.
2. Then test yourself with [Tree Interview Questions](/posts/tree-interview-questions/).
3. Preparing for a university exam? See [Tree Questions for University Exams in Bangladesh](/posts/tree-questions-university-exams-bangladesh/).
