Data Structures Trees Interview Questions and Answers

1

Describe Trees using C++ with an example.

Tree is a structure that is similar to linked list. A tree will have two nodes that point to the left part of the tree and the right part of the tree. These two nodes must be of the similar type.

The following code snippet describes the declaration of trees. The advantage of trees is that the data is placed in nodes in sorted order.

struct TreeNode
{
int item; // The data in this node.
TreeNode *left; // Pointer to the left subtree.
TreeNode *right; // Pointer to the right subtree.
}

The following code snippet illustrates the display of tree data.

void showTree( TreeNode *root )
{
if ( root != NULL ) { // (Otherwise, there's nothing to print.)
showTree(root->left); // Print items in left sub tree.
cout << root->item << " "; // Print the root item.
showTree(root->right ); // Print items in right sub tree.
}
} // end inorderPrint()

2

What is a B tree?

A B-tree of order m (the maximum number of children for each node) is a tree which satisfies the following properties :

Every node has <= m children.

Every node (except root and leaves) has >= m/2 children.

The root has at least 2 children.

All leaves appear in the same level, and carry no information.

A non-leaf node with k children contains k – 1 keys

3

What are splay trees?

A splay tree is a self-balancing binary search tree. In this, recently accessed elements are quick to access again

It is useful for implementing caches and garbage collection algorithms.

When we move left going down this path, its called a zig and when we move right, its a zag.

Following are the splaying steps. There are six different splaying steps.

Zig Rotation (Right Rotation)

Zag Rotation (Left Rotation)

Zig-Zag (Zig followed by Zag)

Zag-Zig (Zag followed by Zig)

Zig-Zig

Zag-Zag

4

Explain red-black trees?

A red-black tree is a type of self-balancing binary search tree.
In red-black trees, the leaf nodes are not relevant and do not contain data.
Red-black trees, like all binary search trees, allow efficient in-order traversal of elements.
Each node has a color attribute, the value of which is either red or black.

Characteristics:
The root and leaves are black
Both children of every red node are black.
Every simple path from a node to a descendant leaf contains the same number of black nodes, either counting or not counting the null black nodes

5

What are threaded binary trees?

In a threaded binary tree, if a node 'A' has a right child 'B' then B's left pointer must be either a child, or a thread back to A.

In the case of a left child, that left child must also have a left child or a thread back to A, and so we can follow B's left children until we find a thread, pointing back to A.

This data structure is useful when stack memory is less and using this tree the treversal around the tree becomes faster.

FOLLOW US