forked from VinayBelwal/Hactober-22-Programs-and-Projects-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Right_view_Binary_tree.cpp
65 lines (55 loc) · 1.39 KB
/
Right_view_Binary_tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// C++ program to print right view of Binary Tree
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
// A utility function to
// create a new Binary Tree Node
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 last Node of its level
if (*max_level < level) {
cout << root->data << "\t";
*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);
}
// A wrapper over rightViewUtil()
void rightView(struct Node* root)
{
int max_level = 0;
rightViewUtil(root, 1, &max_level);
}
// Driver Code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->right->right = newNode(8);
rightView(root);
return 0;
}