-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreeTraversals.cpp
98 lines (85 loc) · 2.19 KB
/
treeTraversals.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
#include <bits/stdc++.h>
using namespace std;
/*
A Tree is also technically a graph with N nodes and N-1 edges.
Level order traversal of a binary tree is similar to doing a Breadth-first search on a graph.
DFS is dfs, no variations.
structure of the tree node we will be using.
*/
typedef struct node
{
int val;
node *left;
node *right;
} node;
/*
I will just print the values. Modify as you wish.
*/
void levelOrderTraversal(node *root)
{
if (root == nullptr)
return;
queue<pair<node *, int>> q;
int curDepth = 0;
q.push({root, curDepth});
while (!q.empty())
{
node *top = q.front().first;
int depth = q.front().second;
q.pop();
if (depth > curDepth)
{
cout << endl; // print a new line to show we are one level deeper.
curDepth = depth;
}
cout << top->val << " ";
// elements are pushed in left to right manner
if (top->left != nullptr)
q.push({top->left, depth + 1});
if (top->right != nullptr)
q.push({top->right, depth + 1});
}
cout << endl; // print new line after last level in the tree.
}
/**
N-ary Tree Level Order Traversal.
struct used to represent an N-ary tree node.
**/
typedef struct NAryTreeNode
{
int val;
vector<NAryTreeNode *> children;
} NAryTreeNode;
/*
The way we handle children of the root node changes, everything else is the same.
*/
void levelOrderTraversal(NAryTreeNode *root)
{
if (root == nullptr)
return;
queue<pair<NAryTreeNode *, int>> q;
int curDepth = 0;
q.push({root, curDepth});
while (!q.empty())
{
NAryTreeNode *top = q.front().first;
int depth = q.front().second;
q.pop();
if (depth > curDepth)
{
cout << endl; // print a new line to show we are one level deeper.
curDepth = depth;
}
cout << top->val << " ";
// elements are pushed in left to right manner
for (NAryTreeNode *child : top->children)
{
q.push({child, depth + 1});
}
}
cout << endl; // print new line after last level in the tree.
}
int main()
{
return 0;
}