• LeetCode 102: Binary Tree Level Order Traversal


    /**
     * 102. Binary Tree 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>> levelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if(root==null) return res;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while(!queue.isEmpty()){
                int cnt = queue.size();
                List<Integer> level = new ArrayList<>();
                for(int i=0;i<cnt;i++){
                    TreeNode tmp = queue.poll();
                    level.add(tmp.val);
                    if(tmp.left!=null)
                        queue.add(tmp.left);
                    if(tmp.right!=null)
                        queue.add(tmp.right);
                }
                res.add(level);
            }
            return res;
        }
    }
    
    // 2. Time:O(n)  Space:O(n)
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            helper(root,1,res);
            return res;
        }
        
        public void helper(TreeNode root, int level, List<List<Integer>> res){
            if(root==null) return;
            if(level>res.size())
                res.add(new ArrayList<>());
            res.get(level-1).add(root.val);
            helper(root.left,level+1,res);
            helper(root.right,level+1,res);
        }
    }
    
  • 相关阅读:
    抖动代码
    WSAWaitForMultipleEvents()
    udp 不需要 listen
    WSAEventSelect
    C++ Win32控制台应用程序捕捉关闭事件
    玩转Win32开发(2):完整的开发流程
    win32线程池代码(WinApi/C++)
    又线程类封装
    Win2 Socket(套接字)相关 API
    Win32函数Sleep的精度测试
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12785820.html
Copyright © 2020-2023  润新知