# Frequently asked questions in Tree Data Structures

### 1. What is a tree data structure, and what are its properties?

- When representing hierarchical relationships between data pieces, a non-linear data structure called a tree is utilized. The structure is made up of nodes and edges, where each node holds a value and the edges show the connections between the nodes.
- Following are some characteristics of a tree data structure:
- 1. The tree's top node, known as the root node, is the only one that exists.
- 2. The tree's nodes are all connected by at least one child node.
- 3. Leaf nodes are defined as nodes with no child nodes.
- 4. The maximum number of edges between a tree's root node and leaf node is the tree's height.
- Trees can be either ordered or unordered, meaning that the order of the child nodes can either be fixed or arbitrary.
- Trees can be balanced or unbalanced, meaning that the depth of the nodes can either be equal or not.
- Trees are used in many computer science applications, including file systems, database indexing, and computer networking.

### 2. What are the types of trees, and what are the differences between them?

There are mainly two types of trees data structures:

- Binary Trees: The left child and the right child of each node in a binary tree, a particular form of tree data structure, are its only two possible offspring. When compared to the parent node, the left child is always either smaller or equal to it, whereas the right child is always larger. Heaps, binary search trees, and other types of data structures can all be implemented using binary trees.
- N-ary Trees: Each node in a tree data structure known as an n-ary tree is capable of having n or more offspring. Organization charts, XML documents, and file systems are examples of hierarchical structures that are represented by N-ary trees. They are also used in game development for representing game objects and game levels.

- The following are the main distinctions between binary trees and n-ary trees:
- • Each node in a binary tree can have a maximum of two children, whereas each node in an n-ary tree can have a maximum of n children.
- Binary trees are commonly used for searching and sorting algorithms, while n-ary trees are used for representing hierarchical structures.
- Binary trees have a simple structure, which makes them easy to implement and traverse, while n-ary trees can have a more complex structure, which can make them harder to implement and traverse.
- Binary trees are typically faster than n-ary trees in terms of search and traversal operations, but n-ary trees can store more information per node.

### 3. What is a binary tree, and how is it different from other types of trees?

The left child and the right child of each node in a binary tree, a particular form of tree data structure, are its only two possible offspring. When compared to the parent node, the left child is always either smaller or equal to it, whereas the right child is always larger. Binary trees can be used to implement binary search trees, heaps, and other data structures.

The main difference between binary trees and other types of trees is the number of children each node can have. Other types of trees, such as n-ary trees, can have more than two children per node, which makes them suitable for representing hierarchical structures such as file systems, XML documents, and organization charts.

Binary trees have a simple structure, which makes them easy to implement and traverse. Binary search trees, which are a type of binary tree, are commonly used for searching and sorting algorithms because they allow for efficient searching and inserting operations. Heaps, which are also a type of binary tree, are used for implementing priority queues and sorting algorithms.

Overall, the simplicity and efficiency of binary trees make them a popular choice for implementing a wide range of algorithms and data structures.

### 4. How do you implement a tree data structure in programming languages like C++, Java, or Python?

Nodes must be defined using a class or a structure in order to implement a binary tree.

As a data structure, hierarchical data is often represented or stored as a binary search tree. The term "binary tree" refers to a tree data structure where each node contains two (or a maximum of two) child nodes that make up the tree branches. Left and right child nodes are the names given to these child nodes.

### 5. What is the difference between a binary search tree and a binary tree?

- Each node in a binary tree can have up to two child nodes, making it a nonlinear data structure. A binary tree with nodes and two more binary search trees on either side of it is referred to as a binary search tree (BST).

- The operations of entering, deleting, and locating Binary Trees take much longer since they are not ordered. An element can be added, removed, and searched more quickly in a BST than in a Binary Tree because of its ordered properties.

- A binary tree doesn't have any ordering in terms of the positions of the nodes. Elements found in a BST that are smaller than the nodes element are located in the left subtree, whilst elements that are larger than the nodes element are found in the right subtree.

- The representation of data in a binary tree is carried out in a structure that is hierarchical. In a binary search tree, data is represented in an ordered manner.

- The time complexity for binary tree will be O(N) whereas the time complexity for the binary search tree will be O(N * log(N)).

- A quick and effective way to look for data and get information is using a binary tree. The removal of elements, addition of new ones, and finding of items are all accomplished using the Binary Search Tree.

- Binary Tree serves as the foundation for the creation of several other binary tree architectures, including Complete Binary Tree, BSTs, and Perfect Binary Tree, among others. Binary Search Trees are used to create balanced binary search trees, including AVL Trees, Red Black Trees, and other structures of a like kind.

### 6. What are the basic tree traversal algorithms, and how do you implement them?

A process called traversal visits every node in a tree and has the option of printing their values. Since every node is connected via an edge, we always begin at the root (head) node. (links). In other words, it is impossible for us to pick a tree node at random. There are three methods humans employ to move through a tree.

- In order Traversal
- Pre order Traversal
- Post order Traversal

In order Traversal:

The left subtree, the root, and subsequently the right subtree are all visited in this traversal technique. The possibility that each node could be a subtree by itself should always be kept in mind. A binary tree that is explored in order will generate key values sorted in ascending order.

Algorithm:

Until all nodes are traversed -

Step 1 - Recursively traverse left subtree.

Step 2 - Visit root node.

Step 3 - Recursively traverse right subtree.

Pre order Traversal:

This traversal method visits the root node, the left subtree, and then the right subtree in that order.

Algorithm:

Until all nodes are traversed -

Step 1 - Visit root node.

Step 2 - Recursively traverse left subtree.

Step 3 - Recursively traverse right subtree.

Post order Traversal:

Since the root node is visited last in this traversal mode, the name is appropriate. First we go through the left subtree, then the right subtree, and finally the root node.

Algorithm:

Until all nodes are traversed -

Step 1 - Recursively traverse left subtree.

Step 2 - Recursively traverse right subtree.

Step 3 – Visit root node.

### 7. How do you perform operations like insert, delete, and search in a binary search tree?

A binary search tree is a binary tree data structure built on nodes that has the following features:

In a node's left subtree, only nodes with keys lower than the node's key are present.

In a node's right subtree, only nodes with keys greater than the node's key can be found.

A binary search tree must also be present in each of the left and right subtrees.

There cannot be any duplicate nodes.

We can perform three operations on the Binary Search Tree. They are:

- Insert operation
- Search operation
- Delete operation

Insert a node in a Binary Search Tree:

At the leaf, a fresh key is constantly inserted. From the root node all the way to a leaf node, we start looking for a key. The new node is inserted as a child of the leaf node as soon as one is discovered.

Steps for inserting a node in the Binary Search Tree:

- Start traversing from the root node.
- The inserting element is compared to the root; if it is less, the left subtree is called recursively; otherwise, the right subtree is called recursively.
- Whenever you've reached the end, simply insert that node to the left (if smaller than the current) or to the right.

### Search for a node in a Binary Search Tree:

If we had an array that was sorted, we could have used a binary search to look up a value. The entire list is first designated as the search space if we want to find a specific number in the array.

The number is limited to this search area. Currently, we compare the amount to be searched or the element to be searched with the middle element (median) of the search space. If the record being searched is less than the middle element, we search in the left half; if not, we search in the right half.

If the two comparisons are equal, the element has been found. In binary search, we start with "n" items in the search space, and we limit the search space to "n/2" if the mid element is not the element we are seeking for. When there is just one element left in the search space, the reduction is finished. We continue to narrow the search space until we either locate the desired record or until there is no more room left for the search.

It will be pretty similar to conduct searches in binary search trees. In a binary search tree, all of the elements on the left are smaller while all of the elements on the right are larger.

As a result, if we wish to locate a number, we start at the root and compare the value being sought with the value of the root. If the values are equal, the search is complete; however, if the values are smaller, we need to move to the left subtree.

This traversal basically represents the process of finding an element in a binary search tree; each time, one subtree is discarded and we move left or right, depending on the stepIf the tree is balanced, we start with a search space of 'n' nodes and as we eliminate one of the sub-trees, we eliminate 'n/2' nodes, reducing our search space to 'n/2'.

(We refer to a tree as balanced if for all nodes the difference between the heights of the left and right subtrees is not greater than one).

The search space is then shrunk to "n/4," and the process is repeated until the element is found or until there is only one node left in the search area. The term "Binary Search Tree" refers to the fact that the search in this case is also a binary search.

### Delete a node in a Binary Search Tree:

Depending on where the node to be destroyed is located, the Binary Search Tree's deletion operation can be carried out.

Deletion of a node having

- 0 children
- 1 children
- 2 children

Steps for deletion of a node in a Binary Search Tree:

- Return root if the root is NULL (Base case)
- Set root->left = deleteNode(root->left, key) if the key is less than the value of the root.
- If the value of the key exceeds that of the root, set root->right = deleteNode(root->right, key).
- If not, check
- If the root is a leaf node, then return null; otherwise, if the root has only one child, then return the left child; otherwise, if the root has only one child, then return the right child; otherwise, set the value of the root as of its inorder successor and recur to delete the node with the value of the inorder successor.
- Return.

### 8. What are AVL trees, and what is their significance in computer science?

By GM Adelson-Velsky and EM Landis, the AVL Tree was created in 1962. To honour the creators, the tree is given the name AVL.

Every node in a height-balanced binary search tree, also known as an AVL tree, is given a balancing factor, which is calculated by subtracting the height of the node's right sub-tree from the height of its left sub-tree.

The balance factor of each node in a tree must be between -1 and 1, or else the tree must be balanced, in order for it to be deemed balanced.

Balance Factor (k) is equal to the height of the left and right sides combined.

The left sub-tree is one level higher than the right sub-tree if any node's balancing factor is 1, which proves this.

If any node's balancing factor is 0, the height of the left sub-tree and the right sub-tree are equal.

The left sub-tree is said to be one level behind the right sub-tree if a node has a negative balancing factor.

A diagram of an AVL tree is shown in the accompanying figure. The related balance factor for each node, as we can see, varies from -1 to +1.

By preventing it from becoming skewed, the AVL tree regulates the height of the binary search tree. With a binary search tree of height h, the total time required for all operations is O (h). However, if the BST becomes skewed, it can be extended to O(n) (i.e. worst case). The AVL tree puts an upper bound on each operation to be O(log n), where n is the number of nodes, by limiting this height to log n.

### 9. What are red-black trees, and how do they differ from AVL trees?

Red-black trees and AVL trees are two popular types of self-balancing binary search trees that efficiently maintain a sorted set of elements.

Red-black trees are designed to be efficient and easy to implement, while still maintaining good balance. They are based on a simple set of rules that ensure the tree remains balanced: each node is either red or black, the root is black, all leaves are black, and if a node is red, then its children must be black. These rules ensure that the longest path from the root to a leaf is no more than twice as long as the shortest path, which guarantees that the tree is balanced and maintains a logarithmic height.

AVL trees, on the other hand, are designed to be more strictly balanced than red-black trees. In an AVL tree, the heights of the left and right subtrees of every node differ by at most one. To maintain this balance, AVL trees use a more complex set of rules and rotations that can require more processing time and memory than red-black trees.

The key differences between red-black trees and AVL trees are:

- Balance criteria: Red-black trees are less strictly balanced than AVL trees, which can result in faster insertion and deletion times, but slower searching times.
- Rotations: AVL trees require more rotations to maintain their balance, while red-black trees require fewer.
- Memory usage: AVL trees require more memory than red-black trees due to the need to store additional balance information in each node.

In summary, red-black trees and AVL trees are both efficient and effective methods of maintaining sorted sets of data. Red-black trees provide a good balance between speed and balance criteria, while AVL trees are more strictly balanced, but require more processing time and memory. The choice between them depends on the specific requirements of the application.

### 10. How do you balance a binary search tree?

To explore nodes in order and place each one one at a time into an AVL tree that self-balances like a BST is a simple solution. This solution's time complexity is O (n Log n), and it does not guarantee the AVL tree's lowest height because it is conceivable for the AVL tree's height to be as high as 1.44 * log (2n) in the worst case.

We can construct an efficient solution which helps to convert a normal binary search tree into a balanced binary search tree. We have a few steps below.

Go through the provided BST in sequence, then save the results in an array. The duration of this phase is O(n). Because BST always creates sorted sequences, it should be noted that this array would be sorted.

Using the recursive strategy described here, generate a balanced BST using the array of sorted values created earlier. The processing of an element takes O(1) time, hence this step also takes O(n) time because we traverse each element precisely once.

### 11. What is a trie, and how is it used in computer science?

Trie is a particular kind of k-ary search tree that is employed for both storing and searching a certain key out of a collection. Trie can be used to reduce search complexity to the ideal level (key length).

Strings written in an alphabet can be stored in a multiway tree data structure called a trie (derived from retrieval). It is employed to store a significant number of strings. Using attempts, the pattern matching can be carried out effectively.

Words like plenty, alone, ant, and, are, bat, bad, are displayed in the trie. All strings with a same prefix should originate from the same node, according to the theory. Programs for testing spelling make advantage of the trials.

The efficiency of the method for pattern matching is increased by preprocessing patterns. Therefore, preprocessing the text rather than using a pattern for effective search is preferable when a text is too vast.

A trie is a type of data structure that enables pattern matching requests in time that is proportional to the size of the patterns.

In the case of storing keys in a binary search tree, the time required by a well-balanced BST will be M * log N, where M is the maximum string length and N is the total number of keys in the tree. The key can be looked up using Trie in O(M) time. However, the Trie storage needs are penalised.

**Structure o a Trie Node:**

The Trie graph has many branches at each node. The conceivable character of each branch's key symbolises it. Note that the word "node" ends at the last node of each key. It is possible to identify a node as the end of a word using the Trie node field isEndOfWord.

**Insert operation on a Trie Node:**

It is straightforward to enter a key into Trie.

An individual Trie node is placed for each character of the input key. The children is an array of pointers (or references) to next-level trie nodes, as you may have noticed.

As an index to the array's kids, the key character serves as a key.

Create new nodes for the input key if it is brand-new or an extension of an existing one, and then place a word-ending symbol after the final node.

Whenever a key in Trie has an input key that is a prefix of another key, Just indicate a word's end at the final node of the key.

**Advantages of Tries:**

- The keys are looked up using frequent prefixes in tries. It is hence quicker. In the case of a binary search tree, the height affects the key lookup.
- When there are several short strings in a try, it takes up less room. As shared nodes exist between the keys.
- when trying to find the key, tries to assist with longest prefix matching.

**Search operation in Tries:**

The insert action is comparable to finding a key. The only thing it does is move down and compare the characters. When a string ends or there is no key in the trie, the search may come to an end.

The key is present in the trie in the first scenario if the isEndofWord field of the last node is true.

### 12. What is a segment tree, and what are its applications in computer science?

A segment tree, often referred to as a statistic tree in computer science, is a type of tree data structure used to store details about intervals, or segments. It enables searching for segments that contain a specific point among those that have been stored. In theory, it is a static construction that cannot be altered once it has been constructed.

Applications of a segment Tree in Computer Science:

The segment tree data structure can be used to address a number of issues, including:

- Range Min, Max, and Sum Queries, as well as Range Update Queries
- maximum create, query, and update segments in a segment tree.
- building, querying, and updating a segment tree with minimum.
- Computational geometry is a branch of mathematics that deals with the creation and evaluation of effective algorithms for the solution of geometric I/O issues. It describes sound modelling algorithms and is also used for pattern recognition.
- Systems that employ data that is tied to a specific location and evaluate and produce geographically related information are known as geographic information systems.
- Section storing in an arbitrary way.
- used in programming that is competitive.
- To determine how frequently certain items occur within a range, segment trees can be utilised.
- For image processing tasks, segment trees may be used.

### 13. What is a heap, and how is it related to trees?

A Heap is a unique type of tree-based data structure where the tree is a full binary tree.

- A type of Tree itself is a heap. The tree not a kind of heap, the tree.
- Max-Heap and Min-Heap are the two most common forms of heaps. In contrast, a tree can be of many different sorts, such as a binary tree, a binary search tree (BST), an AVL tree, etc.
- In the worst situation, inserting and removing data will need O(log(N)) time. In the worst case scenario where the tree is skewed, inserting and removing will need O(N) time.
- In the appropriate Min/Max heap, finding the minimum or maximum value takes O(1) time. Finding the Min/Max value in BST is O(log(N)), and finding it in a binary tree is O (N).
- Priority Queue and Heap are both synonyms for the same thing. A connected undirected graph without a cycle can alternatively be referred to as a tree.

### 14. What are the advantages and disadvantages of using trees as a data structure?

### Advantages of using the Tree Data Structure:

- Quick Search: Because trees have a hierarchical structure that makes it possible to navigate them with ease, they make it possible to quickly search for and retrieve information.
- Organization: Trees are effective for setting up a hierarchical structure for data, which makes it simple to navigate and handle massive volumes of data.
- Flexibility: Trees are versatile representational tools that may be modified to a variety of applications and used to represent a broad range of relationships.
- A tree may be efficiently added to and removed from.
- The number of nodes in a tree is not constrained because they are dynamic in nature.

### Disadvantages of using the Tree Data Structure:

- Imbalanced Trees: A tree that is out of balance might make it difficult to find information and retrieve it.
- Trees can be complicated, particularly when working with big trees or when the structure is not clearly specified.
- Memory Overhead: Trees can have a significant memory overhead, particularly when dealing with very deep trees or when storing big volumes of data.

### 15. What is the time complexity of common operations in a binary search tree, and how do they differ from other data structures?

Binary Tree Operations:

Element 2 needs to be searched, so we must go through every element (assuming we do breadth first traversal). In light of this, the worst-case complexity of binary tree searching is O. (N).

The elements must be traversed in order to place an element as the left child of element 2. Because of this, insertion into a binary tree has a worst-case complexity of O (N).

We must go through all of the items to discover element 2 in order to delete it (assuming we do breadth first traversal). The worst case complexity of deletion in a binary tree is therefore O (N).

Binary search Tree Operations:

Searching: To search element 1, we must navigate through all of the elements (in order 3, 2, 1). The worst case complexity of binary search tree search is therefore O. (n). Generally speaking, the temporal complexity is O(h), where h is the BST height.

Element 0 must be put as the left child of element 1, then it can be placed. As the worst-case complexity of inserting 0 has an O complexity, we must visit all of the elements (in the order 3, 2, 1) to do so (n). Typically, O represents temporal complexity (h).

We must go through all of the elements to find element 1 in order to delete it (in order 3, 2, 1). The worst case complexity of deletion in a binary tree is therefore O. (n). Typically, O represents temporal complexity (h).

**AVL Height Balanced Tree:**

Searching: To search for element 1, we must go through the elements in the following order: 5, 4, 1, = 3 = log2n. As a result, searching in the AVL tree has a worst-case complexity of O. (log2n).

Element 12 must be included as the correct child of element 9, in order to be inserted. As a result, we must traverse the elements (in the order of 5, 7, and 9) to insert 12, which has a worst-case complexity of O. (log2n).

Elements must be traversed in order to find element 9 in order to delete it (in order 5, 7, 9). As a result, deletion in a binary tree has a worst-case complexity of O. (log2n).