forked from shivaylamba/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Left View of a binary tree
59 lines (49 loc) · 1.12 KB
/
Left View of a binary tree
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
// C++ program to print left
// view of Binary Tree
#include <bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node *left, *right;
};
// A utility function to create a new Binary Tree node
node* newNode(int item)
{
node* temp = new node();
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
// Recursive function to print left view of a binary tree.
void leftViewUtil(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) {
cout << root->data << "\t";
*max_level = level;
}
// Recur for left and right subtrees
leftViewUtil(root->left, level + 1, max_level);
leftViewUtil(root->right, level + 1, max_level);
}
// A wrapper over leftViewUtil()
void leftView(node* root)
{
int max_level = 0;
leftViewUtil(root, 1, &max_level);
}
// Driver code
int main()
{
node* root = newNode(12);
root->left = newNode(10);
root->right = newNode(30);
root->right->left = newNode(25);
root->right->right = newNode(40);
leftView(root);
return 0;
}