题目:
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)例如:
给定的二叉树是{3,9,20,#,#,15,7},结果输出为:
[
[3],
[20,9],
[15,7]
]
已经对二叉树相关的题产生好感了,(可能是还没有受到二叉树的毒打,但是感觉掌握了二叉树的几种遍历后,做题会有思路一点) ,这道题是“之”字形遍历,看上去很复杂的样子,其实就是变相的层序遍历。首先正常的层序遍历的话需要用到队列来作为辅助,由于队列是先进先出,这样也保证了能够按照顺序去遍历对应层次的孩子节点,但是对于“之”字形,会有逆向的层序遍历,因此需要使用堆来作为辅助,首先将root压栈,pop出后,判断下一层应该是顺序的层序还是逆序的层序,这里使用一个boolean类型变量来记录当前的遍历顺序,使用一个辅助堆来构建下一层的遍历顺序,由于是根节点,下一层为逆序,应该先遍历right节点,所以先将left压栈,再将right压栈,重复上述操作,当一层遍历结束后,对堆栈重新赋值,修改遍历顺序,进行下一层的遍历。
完整代码如下:
public static ArrayList<ArrayList<Integer>> zigzagLevelOrder (TreeNode root) {
// write code here
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if(root==null) {
return res;
}
Stack<TreeNode> nodes = new Stack<>();
Stack<TreeNode> tempNodes = new Stack<>();
ArrayList<Integer> tempRes = new ArrayList<>();
nodes.push(root);
boolean dire = true; //false为右 true左
while (!nodes.empty()) {
TreeNode now = nodes.pop();
if(now!=null) {
tempRes.add(now.val);
}
if(!dire&&now!=null) { //右行
tempNodes.push(now.right);
tempNodes.push(now.left);
}
if(dire&&now!=null) { //左行
tempNodes.push(now.left);
tempNodes.push(now.right);
}
if (nodes.isEmpty()) {
dire = !dire;
nodes = tempNodes;
tempNodes = new Stack<>();
if(tempRes.size()!=0) {
res.add(tempRes);
}
tempRes = new ArrayList<>();
}
}
return res;
}