-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeftViewOfBinaryTree.cpp
More file actions
101 lines (82 loc) · 2.33 KB
/
Copy pathLeftViewOfBinaryTree.cpp
File metadata and controls
101 lines (82 loc) · 2.33 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Q109 https://www.codingninjas.com/codestudio/problems/920519?topList=striver-sde-sheet-problems&utm_source=striver&utm_medium=website
//Recursive Solution
// Time: O(h) h=height
void help(TreeNode<int> *root, vector<int> &ans, int level){
if(root==NULL) return;
if(ans.size()==level) ans.push_back(root->data);
help(root->left,ans,level+1);
help(root->right,ans,level+1); // change above and this line for Right view
}
vector<int> getLeftView(TreeNode<int> *root)
{
vector<int> ans;
help(root,ans,0);
return ans;
}
// Time: O(n)
// https://www.techiedelight.com/print-left-view-of-binary-tree/
//Iterative using queue
#include <iostream>
#include <list>
using namespace std;
// Data structure to store a binary tree node
struct Node
{
int key;
Node *left, *right;
Node(int key)
{
this->key = key;
this->left = this->right = nullptr;
}
};
// Iterative function to print the left view of a given binary tree
void leftView(Node* root)
{
// return if the tree is empty
if (root == nullptr) {
return;
}
// create an empty queue and enqueue the root node
list<Node*> queue;
queue.push_back(root);
// pointer to store the current node
Node* curr = nullptr;
// loop till queue is empty
while (!queue.empty())
{
// calculate the total number of nodes at the current level
int size = queue.size();
int i = 0;
// process every node of the current level and enqueue their
// non-empty left and right child
while (i++ < size)
{
curr = queue.front();
queue.pop_front();
// if this is the first node of the current level, print it
if (i == 1) {
cout << curr->key << " ";
}
if (curr->left) {
queue.push_back(curr->left);
}
if (curr->right) {
queue.push_back(curr->right);
}
}
}
}
int main()
{
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->right = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->left = new Node(7);
root->right->left->right = new Node(8);
leftView(root);
return 0;
}