zoukankan      html  css  js  c++  java
  • 剑指 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. 从上到下打印二叉树

  • 相关阅读:
    bootstrap记忆技巧
    js表单序列化
    bootstrap
    前端调试
    form表单上传文件
    前端调试总结(未完,不一定对)
    serialize()序列化 和serializeArray()和param()
    关于jq插件——表单验证插件
    ModuleNotFoundError: No module named 'PIL'
    自然主键和代理主键的区别
  • 原文地址:https://www.cnblogs.com/fortunely/p/14121557.html
Copyright © 2011-2022 走看看