GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Given a Binary Tree, Print the corner nodes at each level. The node at the leftmost and the node at the rightmost.

Sample input

        1

  2          3

6    5     7    8  

Sample output ->  1 2 3 6 8  10 14

asked Mar 30, 2016 by suryakant

1 Answer

Just do a level order traversal and manipulate that for printing just first and last :

#include <bits/stdc++.h>
using namespace std;

struct bst
{
	bst* left;
	bst* right;
	int data;
	
	bst()
	{
		left = right = NULL;
	}
};

bst* newNode(int data)
{
	bst* r = new bst;
	r->data = data;
	r->left = r->right = NULL;
}

void level(bst *t)
{
	int last = 0;
	bst *star = new bst;
	star->data = -1;
	queue<bst *> q;
	bst *temp=t;
	q.push(t);		q.push(star);
	
	int f = 0;
	while(!q.empty())
	{
		temp = q.front();		q.pop();
		if(f)
		{
			cout << temp->data << "  ";
			f = 0;
		}
		
		if(temp->data == -1)	
		{
			cout << last << "  ";	
			f = 1;
			if(q.size() > 1) 	q.push(star);
		}
		else
		{
			last = temp->data;
			if(temp->left)   	q.push(temp->left);
			if(temp->right)		q.push(temp->right);
		}
	}
}

int main () 
{
    bst* root = newNode(8);
    root->left = newNode(3);
 
    root->left->left = newNode(1);
    root->left->right = newNode(6);
    root->left->right->left = newNode(4);
    root->left->right->right = newNode(7);
 
    root->right = newNode(10);
    root->right->right = newNode(14);
    root->right->right->left = newNode(13);
    
    level(root);
}

 

answered Mar 30, 2016 by utkarsh111
...