- 题目描述
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
来源:LeetCode
- 示例
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
- 思路分析
- 用两个栈倒来倒去就可以了。
- 同一时间必定有一个栈为空,另一个不为空的栈装着当前层次i的所有节点。在每一轮循环,读取这个不为空的栈,并将该栈中的节点的的孩子按照左孩子、右孩子的顺序入栈。当这个栈变为空,另一个栈不为空,且装满了层次i+1的所有节点。此时读取这个不为空的栈并把节点的孩子装入空栈。此时注意,因为是锯齿型读取,所以要先读右孩子,再读左孩子。当这个栈变为空后,开始下一次循环。
- 循环终止条件就是最开始装根节点的栈变为空。
- 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>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList();
Stack<TreeNode> stack1 = new Stack();
Stack<TreeNode> stack2 = new Stack();
if(root == null) return ans;
stack1.push(root);
int last = 1, next = 0;
while(!stack1.empty()) {
List<Integer> temp1 = new ArrayList();
while(!stack1.empty()) {
root = stack1.pop();
temp1.add(root.val);
if(root.left != null) stack2.push(root.left);
if(root.right != null) stack2.push(root.right);
}
ans.add(new ArrayList(temp1));
if(!stack2.empty()) {
List<Integer> temp2 = new ArrayList();
while(!stack2.empty()) {
root = stack2.pop();
temp2.add(root.val);
if(root.right != null) stack1.push(root.right); //这里先装右节点
if(root.left != null) stack1.push(root.left);
}
ans.add(temp2);
}
}
return ans;
}
}