Binary Tree Zigzag Level Order Traversal --- LeetCode

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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


解题思路:  

     题意:按层次遍历二叉树,开始从左到右遍历,下一层从右到左遍历,然后又从左到右遍历,每层遍历完下一层遍历方向相反。

     思路: 首先层次遍历很容易想到使用队列,记录遍历的层次,凡是奇数层将队列中节点的值按顺序添加到链表中,若是偶数层则将队列逆序后添加到链表中。

            然后逆序输出想到了栈。

            最后使用两个栈来遍历该二叉树,一个栈存储当前层次的节点,每pop一个节点,将节点值添加到list中,然后判断该节点是否有孩子节点,若有则将它们压入另外一个栈中。每次循环输出的栈中节点即为树的一层节点。

            注意: 左右孩子节点压入的顺序,需要从左到右输出的层次节点在入栈的时候先压入右孩子。


public class Solution {
    
 public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
          List<List<Integer>> result=new ArrayList<List<Integer>>();
     Stack<TreeNode> stack1=new Stack<TreeNode>();
          Stack<TreeNode> stack2=new Stack<TreeNode>();
          TreeNode node=root;
          if(root==null){
         return result;
          }
          stack1.push(root);
          while(!stack1.isEmpty()||!stack2.isEmpty()){
         List<Integer> data=new ArrayList<Integer>();
         if(!stack1.isEmpty()){
             while(!stack1.isEmpty()){
             node=stack1.pop();
             data.add(node.val);
                 if(node.left!=null){
             stack2.push(node.left);
             }
                      if(node.right!=null){
             stack2.push(node.right);
             }    
             }
             result.add(data);
         }else if(!stack2.isEmpty()){
             while(!stack2.isEmpty()){
             node=stack2.pop();
             data.add(node.val);
             if(node.right!=null){
             stack1.push(node.right);
             }  
             if(node.left!=null){
             stack1.push(node.left);
             }
             }
             result.add(data);
         
         }
                     
          } 
          
       return result;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值