forked from GDSC-IGDTUW-Autumn-of-Code-2022/dsa-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Left View Of Binary Tree.cpp
83 lines (73 loc) · 1.75 KB
/
Left View Of 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Problem Link - https://practice.geeksforgeeks.org/problems/left-view-of-binary-tree/1
#include<bits/stdc++.h>
#define ll int
using namespace std;
// ***********************************************************
// Following is the TreeNode class structure:
template <typename T>
class TreeNode {
public:
T val;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T val) {
this->val = val;
left = NULL;
right = NULL;
}
};
// ***********************************************************
void DFS(TreeNode<ll>* root, ll op, vector<ll> &ans)
{
if(root==nullptr)
return;
if(ans.size()==op)
ans.push_back(root->val);
DFS(root->left,op+1,ans);
DFS(root->right,op+1,ans);
}
TreeNode<ll>* createTree()
{
queue<TreeNode<ll>*> q;
TreeNode<ll> *root = nullptr;
ll val;
cout<<"Enter value of root - "<<endl;
cin>>val;
root = new TreeNode<ll>(val);
q.push(root);
while(q.size())
{
auto cur = q.front();
q.pop();
ll lef,rig;
cout<<"Enter left child of "<<cur->val<<endl;
cin>>lef;
cout<<"Enter right child of "<<cur->val<<endl;
cin>>rig;
if(lef==-1)
cur->left = nullptr;
else
{
TreeNode<ll> *l = new TreeNode<ll>(lef);
cur->left = l;
q.push(l);
}
if(rig==-1)
cur->right = nullptr;
else
{
TreeNode<ll> *r = new TreeNode<ll>(rig);
cur->right = r;
q.push(r);
}
}
return root;
}
int main()
{
TreeNode<ll> *root = createTree();
vector<ll> ans;
DFS(root,0,ans);
for(auto i:ans)
cout<<i<<" ";
}