给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回锯齿形层次遍历如下:
[ [3], [20,9], [15,7] ]
思路:从左到右遍历,下一行是从右往左遍历,交叉往返的之字形的层序遍历。根据其特点我们用到栈的后进先出的特点,这道题我们维护两个栈,相邻两行分别存到两个栈中,进栈的顺序也不相同,一个栈是先进左子结点然后右子节点,另一个栈是先进右子节点然后左子结点,这样出栈的顺序就是我们想要的之字形了,代码如下
/**
* 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>> bb=new ArrayList<List<Integer>>();
Stack<TreeNode> stack1=new Stack<TreeNode>();
Stack<TreeNode> stack2=new Stack<TreeNode>();
TreeNode root1;
if (root == null) return bb;
stack1.push(root);
while (!stack1.empty()||!stack2.empty())
{
List<Integer> aa=new ArrayList<Integer>();
List<Integer> cc=new ArrayList<Integer>();
while(!stack1.empty())
{
root1=stack1.pop();
aa.add(root1.val);
if (root1.left!=null)
{
stack2.push(root1.left);
}
if (root1.right!=null)
{
stack2.push(root1.right);
}
}
if(!aa.isEmpty()) bb.add(aa);
while(!stack2.empty())
{
root1=stack2.pop();
cc.add(root1.val);
if (root1.right!=null)
{
stack1.push(root1.right);
}
if (root1.left!=null)
{
stack1.push(root1.left);
}
}
if(!cc.isEmpty())bb.add(cc);
}
return bb;
}
}