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


    请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推


    解题思路

    这道题可以借助两个栈来实现,用文字不好描述,也许直接看代码会好一些

    import java.util.ArrayList;
    import java.util.Stack;
    public class Solution {
        public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        	// 用来存放结点
            ArrayList<ArrayList<Integer>> list = new ArrayList<>();
            if(pRoot == null) {
                return list; 
            }
            // 判断奇偶层
            int layer = 1;
            // 存放奇数层结点
            Stack<TreeNode> s1 = new Stack<>();
            // 存放偶数层结点
            Stack<TreeNode> s2 = new Stack<>();
            // 先把根结点放入奇数层
            s1.push(pRoot);
            // 如果两个栈都为空,那么就证明所有结点都已遍历完毕
            while(!s1.empty() || !s2.empty()) {
            	// 当前层是奇数层
                if(layer % 2 != 0) {
                	// 存放奇数层的结点
                    ArrayList<Integer> temp = new ArrayList<>();
                    // 把奇数层的结点逐个弹出,用 temp 保存起来
                    // 同时把每个弹出结点的左右子结点压入栈
                    // 要注意栈的特点是后进先出,因此出栈顺序和入栈顺序是相反的
                    while(!s1.empty()) {
                        TreeNode node = s1.pop();
                        if(node != null) {
                            temp.add(node.val);
                            s2.push(node.left);
                            s2.push(node.right);
                        }
                    }
                    if(!temp.isEmpty()) {
                        list.add(temp);
                        layer++;
                    }
                } else {
                	// 原理同上
                    ArrayList<Integer> temp = new ArrayList<>();
                    while(!s2.empty()) {
                        TreeNode node = s2.pop();
                        if(node != null) {
                            temp.add(node.val);
                            s1.push(node.right);
                            s1.push(node.left);
                        }
                    }
                    if(!temp.isEmpty()) {
                        list.add(temp);
                        layer++;
                    }
                }
            }
            return list;
        }
    }
    

  • 相关阅读:
    Insubstantial 6.2 Release
    解决异常:Package should contain a content type part [M1.13]
    Peer-to-Peer 综述
    P2P网络穿越 NAT穿越
    Faster_RCNN 2.模型准备(上)
    Pytorch Visdom
    python opencv3添加opencv-contrib
    Pytorch之验证码识别
    Pytorch tutorial 之Datar Loading and Processing (2)
    Pytorch tutorial 之Datar Loading and Processing (1)
  • 原文地址:https://www.cnblogs.com/Yee-Q/p/14163520.html
Copyright © 2011-2022 走看看