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;
        }
  • 相关阅读:
    学习进度
    作业8:单元测试练习
    用户体验设计案例分析
    团队协作一
    需求分析
    结对编程——词频统计 2
    结对编程——词频统计
    个人项目-词频统计
    数组求和
    个人介绍和Github使用流程
  • 原文地址:https://www.cnblogs.com/kaibing/p/9013358.html
Copyright © 2011-2022 走看看