zoukankan      html  css  js  c++  java
  • 牛客(59)按之字形顺序打印二叉树

    //    题目描述
    //    请实现一个函数按照之字形打印二叉树,
    //    即第一行按照从左到右的顺序打印,
    //    第二层按照从右至左的顺序打印,
    //    第三行按照从左到右的顺序打印,
    //    其他行以此类推。
    
        public class TreeNode {
            int val = 0;
            TreeNode left = null;
            TreeNode right = null;
    
            public TreeNode(int val) {
                this.val = val;
    
            }
    
        }
    
        public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
    
            ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>();
            if (pRoot==null){
                return arrayLists;
            }
    
            Stack<TreeNode> stack1 = new Stack<TreeNode>();
            Stack<TreeNode> stack2 = new Stack<TreeNode>();
            stack1.add(pRoot);
            while (!stack1.isEmpty() || !stack2.isEmpty()) {
                if (!stack1.isEmpty()) {
                    ArrayList<Integer> arrayList = new ArrayList<Integer>();
                    while (!stack1.isEmpty()) {
                        TreeNode node = stack1.pop();
                        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.pop();
                        arrayList.add(node.val);
                        if (node.right != null) {
                            stack1.add(node.right);
                        }
                        if (node.left != null) {
                            stack1.add(node.left);
                        }
                    }
                    arrayLists.add(arrayList);
                }
            }
    
            return arrayLists;
        }
  • 相关阅读:
    暑假集训每日一题0716(BFS)
    HDOJ1754(I Hate It)
    POJ2777(Count Color)
    暑假集训每日一题0717(DFS)
    SPOJ7259(Light Switching)
    cocos2dx CCTextureCache
    写给自己——EntryName命名规则
    观XX项目感1
    观XX项目感2 之 软件工程的图纸(再看UML类图)
    游戏编程 && cocos2d 学习
  • 原文地址:https://www.cnblogs.com/kaibing/p/9109691.html
Copyright © 2011-2022 走看看