GeeksforGeeks » Interview Questions

How to verify if given data structure represents Binary Tree

(3 posts)
  • Started 4 months ago by Verify if Binary Tree
  • Latest reply from gaurav

Tags:

  1. Verify if Binary Tree
    guest
    Posted 4 months ago #

    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 ?

  2. krishna
    guest
    Posted 4 months ago #

    The question is not clear to me. A NULL pointer also represents an empty tree

  3. gaurav
    guest
    Posted 4 months ago #

    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.

RSS feed for this topic