-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathBinary Tree Zigzag Level Order Traversal.js
139 lines (117 loc) · 2.66 KB
/
Binary Tree Zigzag Level Order Traversal.js
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
/**
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var zigzagLevelOrder = function(root) {
var result = [],
cur = [],
left = true,
i,
len,
temp,
next;
if (!root) {
return result;
}
cur.push(root);
while(cur.length > 0) {
len = cur.length;
temp = [];
next = [];
for (i = 0; i < len; i++) {
temp.push(cur[i].val);
if (cur[i].left) {
next.push(cur[i].left);
}
if (cur[i].right) {
next.push(cur[i].right);
}
}
if (!left) {
temp.reverse();
}
left = !left;
result.push(temp);
cur = next;
}
return result;
};
// SOLUTION 2: USE STACK
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var zigzagLevelOrder = function(root) {
var result = [],
cur = [],
left = true,
i,
len,
temp,
next,
node;
if (!root) {
return result;
}
cur.push(root);
while(cur.length > 0) {
len = cur.length;
temp = [];
next = [];
node = cur.pop();
while (node) {
temp.push(node.val);
if (left) {
if (node.left) {
next.push(node.left);
}
if (node.right) {
next.push(node.right);
}
} else {
if (node.right) {
next.push(node.right);
}
if (node.left) {
next.push(node.left);
}
}
node = cur.pop();
}
result.push(temp);
cur = next;
left = !left;
}
return result;
};