LeetCode 102: Binary Tree Level Order Traversal

Posted aaamsl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
}

以上是关于LeetCode 102: Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 102. Binary Tree Level Order Traversal

[LeetCode]题解(python):102- Binary Tree Level Order Traversal

LeetCode 102. Binary Tree Level Order Traversal

Leetcode 102. Binary Tree Level Order Traversal

[leetcode-102-Binary Tree Level Order Traversal]

Java [Leetcode 102]Binary Tree Level Order Traversal