zoukankan      html  css  js  c++  java
  • LeetCode 103: Binary Tree Zigzag Level Order Traversal

    /**
     * 103. Binary Tree Zigzag Level Order Traversal
     * 1. Time:O(n)  Space:O(n)
     * 2. Time:O(n)  Space:O(n)
     */
    
    // 1. Time:O(n)  Space:O(n)
    class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            helper(root,1,res,true);
            return res;
        }
        
        private void helper(TreeNode root,int level,List<List<Integer>> res,boolean order){
            if(root==null) return;
            if(level>res.size())
                res.add(new ArrayList<>());
            if(order) res.get(level-1).add(root.val);
            else res.get(level-1).add(0,root.val);
            helper(root.left,level+1,res,!order);
            helper(root.right,level+1,res,!order);
        }
    }
    
    // 2. Time:O(n)  Space:O(n)
    class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if(root==null) return res;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            boolean order = true;
            while(!queue.isEmpty()){
                ArrayList<Integer> level = new ArrayList<>();
                int cnt = queue.size();
                for(int i=0;i<cnt;i++){
                    TreeNode tmp = queue.poll();
                    if(order) level.add(tmp.val);
                    else level.add(0,tmp.val);
                    if(tmp.left!=null) queue.add(tmp.left);
                    if(tmp.right!=null) queue.add(tmp.right);
                }
                res.add(level);
                order = !order;
            }
            return res;
        }
    }
    
  • 相关阅读:
    php -- 魔术方法 之 对象输出 : __toString()
    php -- each()、list()
    php -- 魔术方法、魔术常量 简单介绍
    webbench
    md5sum/opensll md5
    shopt
    MD5
    print显示特定的数据格式
    gdb调试4--回退
    字符串化#、拼接字符##和可变参数宏(...和_ _VA_ARGS_ _)
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12800840.html
Copyright © 2011-2022 走看看