Binary Tree Level Order Traversal

题目分析

原题链接,登陆 LeetCode 后可用
这道题目就是二叉树的层次遍历,这里借助队列进行实现。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List> levelOrder(TreeNode root) {
        
        List> res = new ArrayList<>();
        Queue q = new LinkedList<>();
        
        TreeNode t = root;
        
        if(t != null) {
            q.offer(t);
        }
        
        while(!q.isEmpty()){
            
            ArrayList level = new ArrayList<>();
            Queue next = new LinkedList<>();

            while(!q.isEmpty()) {
                t = q.poll();
                level.add(t.val);
                if(t.left != null) {
                    next.offer(t.left);
                }
                if(t.right != null) {
                    next.offer(t.right);
                }
            }
            
            res.add(level);
            q = next;
        }
        
        return res;
    }
}

你可能感兴趣的:(Binary Tree Level Order Traversal)