top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to get the Right View of a Binary Tree?

+2 votes
145 views

Given Tree

          6
       /     \
     7        8
   /   \     /  \
  9    10  11    12
                  \
                   13

Expected Output
6 8 12 13

posted Apr 8, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

A simple solution is to do level order traversal and print the last node in every level. Following is the program to get the right side view of the binary tree

struct Node
{
    int data;
    struct Node *left, *right;
};

struct Node *newNode(int item)
{
    struct Node *temp =  (struct Node *)malloc(sizeof(struct Node));
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}

// Recursive function to print right view of a binary tree.
void rightViewUtil(struct Node *root, int level, int *max_level)
{
    // Base Case
    if (root==NULL)  return;

    // If this is the first Node of its level
    if (*max_level < level)
    {
        printf("%d\t", root->data);
        *max_level = level;
    }

    // Recur for right subtree first, then left subtree
    rightViewUtil(root->right, level+1, max_level);
    rightViewUtil(root->left, level+1, max_level);
}


void rightView(struct Node *root)
{
    int max_level = 0;
    rightViewUtil(root, 1, &max_level);
}

int main()
{
    struct Node *root = newNode(6);
    root->left = newNode(7);
    root->right = newNode(8);
    root->left->left = newNode(9);
    root->left->right = newNode(10);
    root->right->left = newNode(11);
    root->right->right = newNode(12);
    root->right->left->right = newNode(13);

    rightView(root);

    return 0;
}

Output

6   8   12  13
answer Apr 10, 2014 by Salil Agrawal
Similar Questions
+6 votes
The input tree is as shown below
            40
            / \
        20      60
        / \       \
    10      30      80
      \            /  \ 
       15        70    90

Output: 15 30 60 80 90
+2 votes

Please share the code or algorithm to delete a node from Threaded Binary Tree.

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...