zoukankan      html  css  js  c++  java
  • leetcode 103. Binary Tree Zigzag Level Order Traversal

    利用双向队列

    偶数层当栈用,

    奇数层当队列用

    class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            
            Deque<TreeNode> dp = new LinkedList<>();
            if(root == null)
                return res;
            
            dp.addFirst(root);
            boolean flag = true;
            
            while(!dp.isEmpty()){
                int size = dp.size();
                List<Integer> level = new ArrayList<>();
                
                for(int i=0; i<size; i++){
                    if(flag){
                        TreeNode cur = dp.removeFirst();
                        System.out.println(cur.val);
                        if(cur.left != null)
                            dp.addLast(cur.left);
                        if(cur.right != null)
                            dp.addLast(cur.right);
                        level.add(cur.val);
                    }else{
                        TreeNode cur = dp.removeLast();
                        
                        if(cur.right != null)
                            dp.addFirst(cur.right);
                        if(cur.left != null)
                            dp.addFirst(cur.left);
                        level.add(cur.val);
                        
                    }
                    
                        
                }
                
                if(!level.isEmpty())
                    res.add(level);
                flag = !flag;
            }
            return res;
        }
    }
  • 相关阅读:
    蓝牙遐想
    BT stack浅入了解
    集合(set)
    字典练习
    数据类型--字典
    数据类型--元组
    字符串
    深浅copy
    python---list
    三种Div高度自适应的方法
  • 原文地址:https://www.cnblogs.com/hwd9654/p/11361471.html
Copyright © 2011-2022 走看看