-
Notifications
You must be signed in to change notification settings - Fork 0
/
039_BinaryTreeZigzagTraversal.cpp
61 lines (50 loc) · 1.28 KB
/
039_BinaryTreeZigzagTraversal.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
#include <bits/stdc++.h>
using namespace std;
/*************************************************************
Following is the Binary Tree node structure
*************************************************************/
template <typename T>
class BinaryTreeNode
{
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
}
};
vector<int> zigZagTraversal(BinaryTreeNode<int> *root)
{
// Write your code here!
queue<BinaryTreeNode<int>*> nodes;
vector<int> result;
bool LtR=true;
if(!root) return result;
nodes.push(root);
while(!nodes.empty()){
int k=nodes.size();
vector<int> temp;
for(int i=0; i<k; i++){
BinaryTreeNode<int>* node=nodes.front();
nodes.pop();
temp.push_back(node->data);
if(node->left){
nodes.push(node->left);
}
if(node->right){
nodes.push(node->right);
}
}
if(!LtR){
reverse(temp.begin(), temp.end());
}
LtR=!LtR;
for(auto num: temp){
result.push_back(num);
}
}
return result;
}