剑指 Offer 32

题目

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / 
  9  20
    /  
   15   7

返回:

[3,9,20,15,7]

提示:

  1. 节点总数 <= 1000

思路

典型的二叉树层次遍历问题,用一个LinkedList作为队列存储结构,存储下一层次待访问结点。
另外,题目要求返回int[] 记录每层结点关键字,可以用一个LinkedList存储,遍历完树后再转化成int[]。

实现代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /**
    * 二叉树层次遍历: 广度优先搜索
    */
    public int[] levelOrder(TreeNode root) {
        if (root == null) return new int[]{};

        Queue<TreeNode> queue = new LinkedList();
        List<Integer> list = new LinkedList();

        queue.offer(root);
        
        while (!queue.isEmpty()) {
            TreeNode t = queue.poll();
            list.add(t.val);

            if (t.left != null)
                queue.offer(t.left);
            if (t.right != null)
                queue.offer(t.right);
        }

        int[] res = new int[list.size()];
        int i = 0;
        for (Integer d: list) {
            res[i++] = d;
        }
        
        /* List 转int[], 效率上面方法更低, 空间复杂度也较高
        int[] res = list.stream().mapToInt(Integer::intValue).toArray();
        */
        return res;
    }
}

剑指 Offer 32 - I. 从上到下打印二叉树

原文地址:https://www.cnblogs.com/fortunely/p/14121557.html