-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day-32.cpp
159 lines (137 loc) · 2.94 KB
/
Day-32.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#include <bits/stdc++.h>
using namespace std;
class TreeNode
{
public:
TreeNode *left;
TreeNode *right;
int val;
TreeNode(int val)
{
this->left = left;
this->right = right;
this->val = val;
}
};
// Sum of Left Leaves
void levelOrder(TreeNode *root, int &sum)
{
queue<TreeNode *> q;
if (root != NULL)
{
q.push(root);
}
while (!q.empty())
{
TreeNode *frontNode = q.front();
if (frontNode == NULL)
{
q.pop();
}
else
{
q.pop();
if (frontNode->left)
{
if (frontNode->left->left == NULL &&
frontNode->left->right == NULL)
{
sum += frontNode->left->val;
}
q.push(frontNode->left);
}
if (frontNode->right)
{
q.push(frontNode->right);
}
}
}
}
int sumOfLeftLeaves(TreeNode *root)
{
int sum = 0;
levelOrder(root, sum);
return sum;
}
// Balanced Binary Tree
bool isbool = true;
int solve(TreeNode *root)
{
if (root == NULL)
return 0;
int l = solve(root->left);
int r = solve(root->right);
int diff = abs(l - r);
if (diff > 1)
{
isbool = false;
}
return max(l, r) + 1;
}
bool isBalanced(TreeNode *root)
{
solve(root);
return isbool;
}
// Binary Tree Inorder Traversal
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> ans;
TreeNode *curr = root;
while (curr)
{
// left node is NULL, then visit it and go right;
if (curr->left == nullptr)
{
ans.push_back(curr->val);
curr = curr->right;
}
// l left node is not null
else
{
// fill inorder predcessor
TreeNode *pred = curr->left;
while (pred->right != curr && pred->right)
{
pred = pred->right;
}
// if pred right node is NULL, then , go left after establishing link from pred to curr;
if (pred->right == nullptr)
{
pred->right = curr;
curr = curr->left;
}
else
{
// left is already visited, Go right after visiting curr node,
pred->right = nullptr;
ans.push_back(curr->val);
curr = curr->right;
}
}
}
return ans;
}
// Count BST Nodes That Lie In a Given Range
void solve2(TreeNode *root, int l, int h, int &cnt)
{
if (!root)
return;
solve2(root->left, l, h, cnt);
if (root->val >= l && root->val <= h)
{
cnt++;
}
solve2(root->right, l, h, cnt);
}
int getCount(TreeNode *root, int l, int h)
{
// your code goes here
int cnt = 0;
solve2(root, l, h, cnt);
return cnt;
}
int main()
{
return 0;
}