103. Binary Tree Zigzag Level Order Traversal

每日一题 2019 - 04 - 23

题目:

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,null,null,15,7],

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

return its zigzag level order traversal as:

1
2
3
4
5
[
[3],
[20,9],
[15,7]
]

解法:

这个题让按照二叉树的层次双数层从右至左、单数层从左至右输出;

具体实现思路如下:

  • 设置一个双端队列用于处理二叉树的结点;

  • 设置一个标记 judge 判断当前的层次的单双数

  • 对单数层进行进行 pop_front 输出,push_back 加入
  • 对双数层进行进行 pop_back 输出,push_front 加入

代码:

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> temp ;
vector<int> cur ;
TreeNode* now = root ;
if(root == NULL)
{
return temp ;
}
deque<TreeNode*> q;
q.push_back(root);
int judge = 0 ;
int number = 1 ;
TreeNode* test = NULL ;
while(q.size() != 0 )
{
for(int i = 0 ; i < number ; i ++)
{
if(judge % 2 == 0)
{
test = q.back();
q.pop_back();
if(test->left)
{
q.push_front(test->left);
}
if(test->right)
{
q.push_front(test->right);
}
}
else
{
test = q.front();
q.pop_front();
if(test->right)
{
q.push_back(test->right);
}
if(test->left)
{
q.push_back(test->left);
}
}
cur.push_back(test->val);
}
judge ++;
number = q.size() ;
temp.push_back(cur) ;
cur.resize(0);
}
return temp ;
}
};
0%
undefined