A Look at the Tree Data Structure in C++ (2024)

Trees can solve a wide variety of computer science problems

A Look at the Tree Data Structure in C++ (3)

Trees are one of the most interesting data structures in computer science. Apart from having common names such as sibling, leaves, parent, child, etc., to represent them, trees can be used to solve some of the most challenging problems in computer science.

Let’s dive into the basic concept of trees, their usage in C++, and their application to some of the most important problems.

Trees belong to the class of non-linear data structures. Unlike linear data structures, such as stacks or lists, where elements are stored in linear order, non-linear data structures store elements hierarchically. Thus the traversal of a tree or graph cannot be completed in a single run.

A typical example of a tree is shown below.

A Look at the Tree Data Structure in C++ (4)

The elements inside the circles are called the nodes of the tree. A binary tree is a data structure where every node has at most two children. The topmost node is called the root node. A node with no children is called a leaf. Here the root node is at 27. The node at 14 is the left child of node 27, and the node at 35 is the right child. Similarly, the left and right children of the parent node 14 are 10 and 19 respectively. The leaves in the above example are 10, 19, 31, and 42. The height of the tree is defined as the longest path from the root to a leaf. In the above case, the height of the tree is 2.

The advantage of trees is that memory is utilized in an efficient way. In the case of a stack, deleting a middle element is difficult since we have to shift the elements to the right of the stack. But in the case of a tree, we can delete the node x and modify its parent node to point to children of x.

Full binary tree: A binary tree is a full binary tree if every node has 0 or 2 children.

Complete binary tree: A binary tree is a complete binary tree if all the levels are completely filled, except possibly the last level, and the last level has all keys as left as possible.

Perfect binary tree: A binary tree is a perfect binary tree if all the internal nodes have two children and all leaf nodes are at the same level.

Balanced binary tree: A binary tree is balanced if the height of the tree is O(Log n) where n is the number of nodes.

Binary search tree: In a binary search tree, a node’s left child must have a value less than its parent’s value and the node’s right child must have a value greater than its parent’s value.

The code to represent a tree in C++ is what is shown below. It consists of a data part and references to the left and right nodes, respectively.

struct node {
int data;
struct node *left; //Reference to left child
struct node *right; //Reference to right child
};

To keep things simple, let’s consider a binary search tree (BST). The basic operations that can be performed on this tree data structure are insert, search, and traversal.

Insert an element into BST

In the example below, we insert an element with value val into the tree. If val is less than the root value, the tree traversal continues to the left since val needs to be inserted in the left subtree. If val is greater than the root value, we continue with a right subtree traversal to insert the val to the right. If val is equal to the root key, we simply return the root to avoid duplicates. If the tree is empty or the tree traversal reaches the end with no result, then we call getNewNode function to get a new node.

Tree traversal and search for an element in a BST

To search for a key in a binary search tree, we check if the root value is equal to NULL. This case happens if the tree is empty or if the tree traversal reaches the end with the key not found. If the key is not present, we return NULL.

If the root value is equal to the key value, we return the root address.

In all other cases, we perform a left tree traversal if the key value is less than the root value and a right tree traversal if the key value is greater than the root value.

Trees can be used to represent hierarchies and structural relationships in data. Also, they are efficient when it comes to insert and search with a time complexity of O(h), where h is the height of the tree. The subtrees can be moved around with minimum effort, unlike with several other data structures, like lists and arrays.

Operating systems

One of the most popular operating systems, Linux, makes use of a tree structure to represent its hierarchical file system. The file system in Linux is arranged in a tree as shown below.

A Look at the Tree Data Structure in C++ (5)

Compilers

A syntax tree is a tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code.

A compiler constructs a syntax tree during the syntax analysis phase of the compiler. This tree is used to check if the correct syntax is followed when coding a computer program.

Bridges and routers

A minimum weight spanning tree is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. This kind of tree is used for packet routing in bridges and routers in computer networks.

Trie

A trie is an efficient information retrieval data structure. Using a trie, search complexities can be brought to optimal limit (key length). If we store keys in a binary search tree, we need time proportional to M * log N, where M is maximum string length and N is the number of keys in the tree. Using a trie, we can search the key in O(M) time.

B-trees, also called self-balancing trees, are used for indexing in databases for efficient information retrieval.

There are several kinds of trees in computer science which can be used for multiple purposes. Trees serve as one of the most important tools that every developer needs to know. This makes problem-solving faster and easier, especially for problems dealing with hierarchy.

A Look at the Tree Data Structure in C++ (2024)

FAQs

What is a tree data structure in C++? ›

A tree data structure is a non-linear data structure because it does not store in a sequential manner. It is a hierarchical structure as elements in a Tree are arranged in multiple levels. In the Tree data structure, the topmost node is known as a root node. Each node contains some data, and data can be of any type.

How do you read a tree data structure? ›

Properties
  1. Follow all properties of binary tree data structure.
  2. Self-balancing.
  3. Each node is either red or black.
  4. The root and leaves nodes are black.
  5. If the node is red, then both children are black.
  6. Every path from a given node to any of its nodes must go through the same number of black nodes.
Feb 20, 2023

What is an example of a tree data structure? ›

Some of the most common real-life applications of tree data structures are folders in an operating system; a Linux file system; and HTML DOM (Document Object Model).

What are the 10 examples of trees? ›

Ans: 10 examples of trees include: Oak tree, Pine tree, Maple Tree, Apple tree, Palm tree, Willow tree, Redwood tree, Birch tree, Fir tree, and Cherry tree.

What is the key in tree data structure? ›

Generally, tree structures store a collection of values called keys. In the above tree, all the listed numbers are keys. He term keys is appropriate since trees often store key/value pairs and the balancing and lookup logic only applies to keys. Hope this helps!

How does tree search work? ›

A tree search starts at the root and explores nodes from there, looking for one particular node that satisfies the conditions mentioned in the problem. Unlike linear data structures, the elements can be traversed in many ways. There are many algorithms that use different order to traverse/pass through a node.

How to solve binary search tree? ›

Algorithm to search for a key in a given Binary Search Tree:
  1. We compare the value to be searched with the value of the root. ...
  2. Repeat the above step till no more traversal is possible.
  3. If at any iteration, key is found, return True.
Nov 21, 2023

What is tree structure view? ›

A tree view is usually a vertical list of nodes arranged in a tree-like structure. Each node represents a single data item, displayed as an indented line of text or a rectangular box. The indentation (and sometimes a line drawn between nodes) is used to indicate levels of hierarchy.

What is a tree in coding? ›

In computer science, a tree is a widely used abstract data type that represents a hierarchical tree structure with a set of connected nodes.

How do you find the inorder of a tree? ›

For Inorder, you traverse from the left subtree to the root then to the right subtree. For Preorder, you traverse from the root to the left subtree then to the right subtree. For Post order, you traverse from the left subtree to the right subtree then to the root.

How to find the degree of a tree? ›

Definition. The degree of a tree represents the maximum degree of a node in the tree. Recall for a given node, its degree is equal to the number of its children. Therefore, to get the degree of a tree we'll use one of the tree traversal methods to iterate over all the nodes of the tree.

What defines a tree data structure? ›

Tree data structure is a hierarchical structure that is used to represent and organize data in a way that is easy to navigate and search. It is a collection of nodes that are connected by edges and has a hierarchical relationship between the nodes.

What is the difference between graph and tree in C++? ›

Graphs do not have a root node. Trees have exactly one root node. Graphs have two traversal techniques namely, breadth−first search and depth−first search. Trees have three traversal techniques namely, pre−order, in−order, and post−order.

What are data structures in C++? ›

  • vectors. In C++, a vector is a data structure that stores a sequence of elements that can be accessed by index. ...
  • Stacks and Queues. In C++, stacks and queues are data structures for storing data in specific orders. ...
  • Sets. In C++, a set is a data structure that contains a collection of unique elements. ...
  • arrays. ...
  • Hash Maps.

What is a tree structure in data model? ›

A tree is a data structure that consists of hierarchy of nodes with a single node, called the root at highest level. dependent. Thus the parent to child relationship in a tree is one to many relationship whereas child to parent relationship in a tree is one to one. example, node 4, 5, 7, 8, 9, 10 and 11.

Top Articles
Latest Posts
Article information

Author: Arline Emard IV

Last Updated:

Views: 5747

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.