码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 102: Binary Tree Level Order Traversal

时间:2020-04-27 13:04:46      阅读:47      评论:0      收藏:0      [点我收藏+]

标签:poll   integer   ==   while   array   add   linked   rsa   int   

/**
 * 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);
    }
}

LeetCode 102: Binary Tree Level Order Traversal

标签:poll   integer   ==   while   array   add   linked   rsa   int   

原文地址:https://www.cnblogs.com/AAAmsl/p/12785820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!