zoukankan      html  css  js  c++  java
  • 牛客(22)从上往下打印二叉树

    //    题目描述
    //    从上往下打印出二叉树的每个节点,同层节点从左至右打印。
        public static class TreeNode {
            int val = 0;
            TreeNode left = null;
            TreeNode right = null;
    
            public TreeNode(int val) {
                this.val = val;
    
            }
    
        }
    
        public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
    //        可以返回个空ArrayList 不能反悔null ,尽量避免返回null 容易引起异常
            ArrayList<Integer> arrayList = new ArrayList<Integer>();
            Queue<TreeNode> stack0 = new LinkedList<TreeNode>();
            Queue<TreeNode> stack1 = new LinkedList<TreeNode>();
            if (root != null) {
                stack0.offer(root);
            }
            while (!stack0.isEmpty() || !stack1.isEmpty()) {
                while (!stack0.isEmpty()) {
                    TreeNode current = stack0.poll();
                    arrayList.add(current.val);
                    if (current.left != null) {
                        stack1.offer(current.left);
                    }
                    if (current.right != null) {
                        stack1.offer(current.right);
                    }
    
                }
                while (!stack1.isEmpty()) {
                    TreeNode current = stack1.poll();
                    arrayList.add(current.val);
                    if (current.left != null) {
                        stack0.offer(current.left);
                    }
                    if (current.right != null) {
                        stack0.offer(current.right);
                    }
    
                }
    
            }
            return arrayList;
        }
  • 相关阅读:
    由PhysicalFileProvider构建的物理文件系统
    Net Core WebApi单元测试
    多个项目使用NET Core
    ReactNative
    定制样式插入到ueditor
    ES6的Class
    Redis存储Session
    二叉 查找树 排序树 搜索树
    SignalR实现实时日志监控
    KNN(k-nearest neighbor的缩写)又叫最近邻算法
  • 原文地址:https://www.cnblogs.com/kaibing/p/9013358.html
Copyright © 2011-2022 走看看