- 题目:按照z字形层次遍历二叉树(以根节点所在层为第1层,则第二层的变量从右边节点开始直到最左边节点,第三层遍历则是从最左边开始到最右边)
- 思路:z字形层次遍历是对层次遍历加上了一个限制条件(即相邻层,从左到右的遍历顺序相反),因此还是可以采用队列来实现,只不过节点接入队列时需要考虑加入的顺序
- 代码:
对节点之间的顺序进行维护
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null){
return result;
}
LinkedList<TreeNode> queue = new LinkedList<>();
int depth = 0;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> tmp = new ArrayList<>();
for(int i = 0; i < size; i++){
TreeNode node = null;
//因为是走z字形,所有相邻两层的节点处理是相反的
if(depth%2 == 0){
node = queue.pollLast();//获取链表最后一个节点
if(node.left != null){
queue.offerFirst(node.left);
}
if(node.right != null){
queue.offerFirst(node.right);
}
}else{
node = queue.poll();//获取链表第一个节点
if(node.right != null){
queue.offer(node.right);
}
if(node.left != null){
queue.offer(node.left);
}
}
tmp.add(node.val);
}
depth++;
result.add(tmp);
}
return result;
}
}
- 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
对节点值之间进行维护,关注点在于值的顺序
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null){
return result;
}
LinkedList<TreeNode> queue = new LinkedList<>();
int depth = 0;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
LinkedList<Integer> tmp = new LinkedList<>();//这里不能申明为将LinkedList泛化为list,否则不能调用addFirst方法
for(int i = 0; i < size; i++){
TreeNode node = queue.poll();
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
if(depth%2 == 0){
tmp.add(node.val);
}else{
tmp.addFirst(node.val);
}
}
depth++;
result.add(tmp);
}
return result;
}
}
- 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
如果不把重点放在节点之间的顺序,可将迭代的实现改成相应的递归实现
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<LinkedList<Integer>> list = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();
if(root == null){
return result;
}
helper(list, root, 0);
result.addAll(list);
return result;
}
public void helper(List<LinkedList<Integer>> result, TreeNode node, int depth){
if(node == null){
return;
}
if(depth == result.size()){
result.add(new LinkedList());
}
if(depth%2 == 0){
result.get(depth).add(node.val);
}else{
result.get(depth).addFirst(node.val);
}
helper(result, node.left, depth+1);
helper(result, node.right, depth+1);
}
}
- 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