Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between node structures of double linked list and binary tree?


I was asked in a interview about the difference between node structures of Doubly linked list and binary Tree.

Doubly Linked List Struct

typedef struct
{
int data;
struct node * next;
struct node * prev;
}node;    

Binary Tree Struct

typedef struct
{
int data;
struct node * left;
struct node * right;
}node;  
  1. In Doubly linked list, we use pointers for traversing back and front in a linearly arranged list.
  2. But where as left & right pointers are used to access the left & right nodes.

I don't find any difference in node structure except the way they are used. Could you please give me some differences???

like image 577
Jeyaram Avatar asked Dec 01 '22 22:12

Jeyaram


1 Answers

I think you have answered your own questions. Other than the obvious differences in names of the pointers (next/prev and left/right), the differences are:

  • In a doubly linked list, if n.next links to m then m.prev links to n. This is not the case in a binary tree.
  • In a doubly linked list, a node can have at most two links to it. In a binary tree, each node has at most one link to it.
  • In a doubly linked list, it is possible to follows links and end up at the node where you started. This is not possible in a binary tree.

If the doubly linked list is also cyclic, the following also holds:

  • In a cyclic doubly linked list with one node, n.next links to n and n.prev also links to n. This is not possible in a binary tree: n.left and n.right do not link to the same node.
  • In a binary tree with one node, n.next and n.prev could point to no node (i.e., the tree is just a leaf node) but in a cyclic doubly linked list with one node both links always have a value (albeit to the same node).
  • In a binary tree it is optional to have a value for either n.left or n.right. If the binary tree is not balanced, it could be that all nodes have a value for n.right but not for n.left. This is not the case for a cyclic doubly linked list where all pointers have a value.

In terms of structure and content the nodes are the same but the differences are in how the pointers are used and what their values can be.

like image 148
Simeon Visser Avatar answered Dec 07 '22 22:12

Simeon Visser