
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
Binary trees are an important part of Computer Science algorithms.
In this tutorial, we’ll look at specific types of binary trees: a full binary tree, a complete binary tree, and a perfect binary tree. We’ll look at the properties of each of these binary trees with illustrations.
A tree is a hierarchical data structure that has a set of connected nodes in a hierarchy like a tree. There is one node, commonly called the root node, which can be connected to a set of child nodes in the form of branches.
When we restrict the tree’s definition to specify that any node can have at most two child nodes attached, this becomes a Binary tree. A binary tree can have a left child node and a right child node.
Binary trees can take many types and forms. A Binary Tree can be categorized based on the properties of the child nodes, the number of child nodes, the height of the subtrees, etc.
Here are a few common binary tree types:
In this tutorial, we’ll focus on the first three.
In this section, we’ll implement a binary tree using recursion. We construct a binary tree of height , which is taken as input:
algorithm CreateBinaryTree(height):
// INPUT
// height = the height of the tree
// OUTPUT
// Returns a binary tree of the specified height
if height = 0:
return null
node <- make a new tree node
node.data <- getSomeData()
node.left <- CreateBinaryTree(height - 1)
node.right <- CreateBinaryTree(height - 1)
return node
A full binary tree is one where every node has either 0 or 2 children:
Properties of a full binary tree:
In a complete binary tree, all levels are filled except the lowest level nodes, which are filled from the left:
Properties of a complete binary tree:
A perfect binary tree, as the name suggests, is the most perfect kind of binary tree with all its nodes with exactly two children, and all leaf nodes at the same level:
Properties of a perfect binary tree:
In this article, we explored the essential properties of full binary trees, complete binary trees, and perfect binary trees.