GeeksforGeeks » Interview Questions
How to verify if given data structure represents Binary Tree
(3 posts)-
Given the following data structure having nodes of the form :
struct node { int data; node* link1; node* link2; }Given node* root , How will you determine if it represents a binary tree or not ?
-
The question is not clear to me. A NULL pointer also represents an empty tree
-
acc to defination of bt,
a bt is a data structure which can be partition in 3 "disjoint" sets ,each of which may contain any no of elements except root (which has only one element)
just to check ,whether given structure represent binary tree or not,
we make use of visited array which keep track of the "nodes" not element already visited .whenever we visit any element just check its corresponding entry in visited array, if it not visited earlier mark it visited ,else given structure does'nt rep bt.
for doing traversal preorder can be choose
void check(tree,int &flag){
if(tree){
if(visited[tree]==false)
visited[tree] =true;
else
flag= false;
check(tree->left);
check(tree->right);}
int result=true;
call check(tree,result);
Reply
You must log in to post.