zoukankan      html  css  js  c++  java
  • 按之字形顺序打印二叉树

    题目描述

    请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
     
    import java.util.ArrayList;
    import java.util.Stack;
    /*
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    
    }
    */
    public class Solution {
        public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
            Stack<TreeNode> stack1 = new Stack<>();
            stack1.push(pRoot);
            int layer = 1;
            Stack<TreeNode> stack2 = new Stack<>();
            ArrayList<ArrayList<Integer>> list = new ArrayList<>();
            while(!stack1.empty() || !stack2.empty()) {
                if(layer%2 != 0) {
                    ArrayList<Integer> temp = new ArrayList<>();
                    while(!stack1.empty()) {
                        TreeNode node = stack1.pop();
                        if(node != null) {
                            temp.add(node.val);
                            stack2.push(node.left);
                            stack2.push(node.right);
                        }
                    }
                    if(!temp.isEmpty()) {
                        list.add(temp);
                        layer++;
                    }
                }else {
                    ArrayList<Integer> temp = new ArrayList<>();
                    while(!stack2.empty()) {
                        TreeNode node = stack2.pop();
                        if(node != null) {
                            temp.add(node.val);
                            stack1.push(node.right);
                            stack1.push(node.left);
                        }
                    }
                    if(!temp.isEmpty()) {
                        list.add(temp);
                        layer++;
                    }
                }
            }
            return list;
        }
    
    }
  • 相关阅读:
    每日日报8月12日
    每日日报8月15日
    每日日报8月18日
    每日日报8月9日
    九月29号——动手又动脑
    今日总结
    每周总结
    今日总结
    周总结
    今日总结
  • 原文地址:https://www.cnblogs.com/yihangZhou/p/10515629.html
Copyright © 2011-2022 走看看