leetcode-中等题-102. 二叉树的层序遍历

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
没什么难度层序遍历,思路清晰多了

  1. 每次出列一个节点,若节点有左右子节点,将他们入列。
  2. 队列空了就停止
  3. 考虑到要分层输出,因此每一次遍历结束之后,统计队列里下一层的长度,逐层输出。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        if(root == null) return res;//特殊情况
        queue.addLast(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> temp = new ArrayList<>();
            for(int i = 0; i < size; i++){
                TreeNode node;
                node = queue.poll();
                if(node.left != null) queue.addLast(node.left);
                if(node.right != null) queue.addLast(node.right);
                temp.add(node.val);
            }
            res.add(temp);
        }
        return res;
    }
}

你可能感兴趣的:(算法,leetcode,算法)