剑指 Offer 32 - III. 从上到下打印二叉树 III
Difficulty: 中等
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3
/
9 20
/
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
提示:
节点总数 <= 1000
Solution
Language: java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null) return new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
Deque<TreeNode> cur1 = new ArrayDeque<>();
Deque<TreeNode> cur2 = new ArrayDeque<>();
Deque<TreeNode> p = cur1;
cur1.push(root);
List<Integer> list = new ArrayList<>();
while(!p.isEmpty()){
TreeNode t = p.pop();
list.add(t.val);
if(p == cur1){
if(t.left != null) cur2.push(t.left);
if(t.right != null) cur2.push(t.right);
}
if(p == cur2){
if(t.right != null) cur1.push(t.right);
if(t.left != null) cur1.push(t.left);
}
if(p.isEmpty()){
res.add(new ArrayList<>(list));
list = new ArrayList<>();
p = p == cur1 ? cur2 : cur1;
}
}
return res;
}
}