-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1. Digonal Traverasal.cpp
84 lines (68 loc) · 1.67 KB
/
1. Digonal Traverasal.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
// https://www.geeksforgeeks.org/problems/diagonal-traversal-of-binary-tree/1
/*
Logic :
1. Start with root and traverse for size of queue , under the while(!Q.emtpy())
2. Put left of nodes in queue and datat of node in ans vector and keep moving right , and do this for size of that queus
*/
// GFG
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left, *right;
};
Node *newNode(int data)
{
Node *node = new Node;
node->data = data;
node->left = node->right = NULL;
return node;
}
vector<vector<int>> result;
void diagonalPrint(Node *root)
{
if (root == NULL)
return;
queue<Node *> q;
q.push(root);
while (!q.empty())
{
int size = q.size();
vector<int> answer;
while (size--)
{
Node *temp = q.front();
q.pop();
// traversing each component;
while (temp)
{
answer.push_back(temp->data);
if (temp->left)
q.push(temp->left);
temp = temp->right;
}
}
result.push_back(answer);
}
}
int main()
{
Node *root = newNode(8);
root->left = newNode(3);
root->right = newNode(10);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->right->right = newNode(14);
root->right->right->left = newNode(13);
root->left->right->left = newNode(4);
root->left->right->right = newNode(7);
diagonalPrint(root);
for (int i = 0; i < result.size(); i++)
{
for (int j = 0; j < result[i].size(); j++)
cout << result[i][j] << " ";
cout << endl;
}
return 0;
}