zoukankan      html  css  js  c++  java
  • 牛客(60)把二叉树打印成多行

        //    题目描述
    //    从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
        public class TreeNode {
            int val = 0;
            TreeNode left = null;
            TreeNode right = null;
    
            public TreeNode(int val) {
                this.val = val;
            }
        }
    
        ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
            ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>();
            if (pRoot == null) {
                return arrayLists;
            }
            Queue<TreeNode> stack1 = new LinkedList<TreeNode>();
            Queue<TreeNode> stack2 = new LinkedList<TreeNode>();
            stack1.add(pRoot);
            while (!stack1.isEmpty() || !stack2.isEmpty()) {
                if (!stack1.isEmpty()) {
                    ArrayList<Integer> arrayList = new ArrayList<Integer>();
                    while (!stack1.isEmpty()) {
                        TreeNode node = stack1.poll();
                        arrayList.add(node.val);
                        if (node.left != null) {
                            stack2.add(node.left);
                        }
                        if (node.right != null) {
                            stack2.add(node.right);
                        }
                    }
                    arrayLists.add(arrayList);
                } else if (!stack2.isEmpty()) {
                    ArrayList<Integer> arrayList = new ArrayList<Integer>();
                    while (!stack2.isEmpty()) {
                        TreeNode node = stack2.poll();
                        arrayList.add(node.val);
                        if (node.left != null) {
                            stack1.add(node.left);
                        }
                        if (node.right != null) {
                            stack1.add(node.right);
                        }
                    }
                    arrayLists.add(arrayList);
                }
            }
            return arrayLists;
        }
  • 相关阅读:
    PDF格式简单分析
    python 2.x 版本 pip 的使用
    网络读书笔记-运输层
    网络读书笔记-应用层
    线程池源码解析
    管道流创建订单
    @autowire、@resource原理
    Spring如何解决循环依赖
    结合Spring特性实现策略模式
    自定义注解+AOP实现redis分布式锁
  • 原文地址:https://www.cnblogs.com/kaibing/p/9109988.html
Copyright © 2011-2022 走看看