Skip to main content

Binary Tree

Author: @wingkwong

Overview

A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. The root node is the topmost node in the tree and the leaf nodes are the nodes at the bottom with no children. Binary trees are commonly used to implement data structures such as binary search trees, which are used for efficient searching and sorting. The height of the binary tree is the number of edges from the root to the deepest leaf node. The depth of a node is the number of edges from the root to that node.

Properties

  • The number of nodes on level ll is equal to the 2l2^l, like on level 00 (root node) we got 20>=12 ^ 0 >= 1 node only.
  • The Maximum number of nodes in a binary tree of height hh is 2h12^h - 1.

Traversal

There are different ways to traverse trees - In-order, Pre-order, and Post-order. Supposing we have a binary tree with 55 nodes,

image

Pre-order

  • Visit the root
  • Traverse the left sub-tree
  • Traverse the right sub-tree
void preorder(TreeNode* node) {
if (node == NULL) return;
s.push_back(node->val);
preorder(node->left);
preorder(node->right);
}

In-order

  • Traverse the left sub-tree
  • Visit the root
  • Traverse the right sub-tree
void inorder(TreeNode* node) {
if (node == NULL) return;
inorder(node->left);
s.push_back(node->val);
inorder(node->right);
}

Post-order

  • Traverse the left sub-tree
  • Traverse the right sub-tree
  • Visit the root
void postorder(TreeNode* node) {
if (node == NULL) return;
postorder(node->left);
postorder(node->right);
s.push_back(node->val);
}

Summary

TraversalPathOrder
Pre-order1 -> 2 -> 4 -> 5 -> 3Root -> Left -> Right
In-order4 -> 2 -> 5 -> 1 -> 3Left -> Root -> Right
Post-order4 -> 5 -> 2 -> 3 -> 1Left -> Right -> Root