lintcode--二叉树的锯齿形层次遍历

给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行) 

样例

给出一棵二叉树 {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

返回其锯齿形的层次遍历为:

[
  [3],
  [20,9],
  [15,7]

]

/**  * Definition of TreeNode:  * public class TreeNode {  *     public int val;  *     public TreeNode left, right;  *     public TreeNode(int val) {  *         this.val = val;  *         this.left = this.right = null;  *     }  * }  */  /*  交叉着走,受上面两题的影响,考虑用队列,发现不可以,换成栈,发现只用一个栈的话也不可以,(一个栈也能对71%的测试数据)在入栈 和出栈的时候,出现了混乱,考虑用两个栈。 下面是自己写的程序,代码写的好燋灼 关键点:两个栈交叉着进,交叉的出*/ public class Solution {     public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {         ArrayList<ArrayList<Integer>> result = new ArrayList<>();         if (root == null)  return result;         Stack<TreeNode> currLevel = new Stack<TreeNode>();         Stack<TreeNode> nextLevel = new Stack<TreeNode>();         currLevel.push(root);         boolean normalOrder = true;         while (!currLevel.isEmpty()) {             ArrayList<Integer> currLevelResult = new ArrayList<Integer>();             while (!currLevel.isEmpty()) {                 TreeNode node = currLevel.pop();                 currLevelResult.add(node.val);                 if (normalOrder == true) {                     if (node.left != null) {                         nextLevel.push(node.left);                     }                     if (node.right != null) {                         nextLevel.push(node.right);                     }                 } else {                     if (node.right != null) {                         nextLevel.push(node.right);                     }                     if (node.left != null) {                         nextLevel.push(node.left);                     }                 }             }             result.add(currLevelResult);             //栈交换             Stack<TreeNode> tmp= currLevel;             currLevel = nextLevel;             nextLevel = tmp;             //设置为相反             normalOrder = !normalOrder;         }         return result;     } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值