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],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
二叉树的之字形层级遍历
这道题做的不错 两种解法都写出来了 不知道为什么第一种比较快 下面的是自己的解法
看了一些discuss 时间复杂度都差不多 只是递归好像快一些 不能太钻牛角尖
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int level = 1;
while (!queue.isEmpty()) {
Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (level % 2 == 0) list.add(0, node.val);
else list.add(node.val);
if(node.left != null) queue2.add(node.left);
if(node.right != null) queue2.add(node.right);
}
level++;
res.add(list);
queue = queue2;
}
return res;
}
第二种做法区别不大 stack化成queue也行 顺序也换一下
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
int level = 0;
while (!stack.isEmpty()) {
Stack<TreeNode> stack2 = new Stack<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
list.add(node.val);
if(level % 2 == 0) {
if(node.left != null) stack2.push(node.left);
if(node.right != null) stack2.push(node.right);
} else {
if(node.right != null) stack2.push(node.right);
if(node.left != null) stack2.push(node.left);
}
}
level++;
res.add(list);
stack = stack2;
}
return res;
}