首页 > 其他分享 >面试必刷TOP101:27、按之字形顺序打印二叉树

面试必刷TOP101:27、按之字形顺序打印二叉树

时间:2023-11-13 20:33:06浏览次数:26  
标签:node queue layer 27 TreeNode val current 之字形 二叉树

题目

面试必刷TOP101:27、按之字形顺序打印二叉树_Stack

题解

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
        // write code here
        ArrayList<ArrayList<Integer>> layers = new ArrayList<ArrayList<Integer>>();

        if (pRoot == null) {
            return layers;
        }

        ArrayList<Integer> layer = new ArrayList<Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();

        // Initialize first node
        layer.add(pRoot.val);
        layers.add(layer);
        queue.offer(pRoot);
        boolean reverse = false;

        while (!queue.isEmpty()) {
            // Reverse flag
            reverse = !reverse;
            layer = new ArrayList<Integer>();

            Stack<Integer> stack = new Stack<Integer>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();

                // Loop for `node.left` and `node.right`
                for (int j = 0; j < 2; j++) {
                    TreeNode current = j < 1 ? node.left : node.right;
                    if (current != null) {
                        // System.out.println(
                        //     node.val + (j < 1 ? ".left = " : ".right = ") + current.val
                        // );

                        if (!reverse) {
                            // Append to result in ascending order
                            layer.add(current.val);
                        } else {
                            // Reverse order for current layer
                            stack.push(current.val);
                        }

                        // Add node to queue for next layer
                        queue.offer(current);
                    }
                }
            }

            // Reverse needed for the current layer
            while (!stack.isEmpty()) {
                layer.add(stack.pop());
            }

            if (layer.size() > 0) {
                layers.add(layer);
            }
        }

        return layers;
    }
}

标签:node,queue,layer,27,TreeNode,val,current,之字形,二叉树
From: https://blog.51cto.com/u_16244372/8352867

相关文章

  • 秦疆的Java课程笔记:27 基础 基本运算符
    Java语言支持的运算符:算数运算符:基础四则运算:+加法,-减法,*乘法,/除法%取余,或称“模运算”++自增,--自减赋值运算符:=关系运算符:>大于,<小于,>=大于等于,<=小于等于==等于,!=不等于instanceof对象运算符,用来判断一个对象是否属于某个指定的类或其子类的实例,如果是,返回true,否则......
  • IPQ9574 vs IPQ9554|QCN9274vs QCN6274|WiFi 7Use Case
    IPQ9574vsIPQ9554vs QCN9274vsQCN6274 IndustrialApplications|WiFi7UseCaseAnticipatingtheFuture:ExploringPotentialUseCasesofWi-Fi7Astechnologycontinuestoevolveatarapidpace,theanticipationforthenextgenerationofwirelessconnecti......
  • 二叉树
    1二叉树的定义:每个结点至多只有两棵子树,并且树的子树有左右之分,其次序不能任意颠倒。2性质:二叉树的第i层最多有2^(i-1)个结点。3深度为k的二叉树最多有2^k-1个结点。4任何一棵二叉树T,如果其终端结点数为n0,度为2的结点数为n2,则n0=n2+1.5一个有n个结点的完全二叉树其深度为log以2......
  • 2023-2024-1 20231427 田泽航 《计算机基础与程序设计》第七周学习总结
    学期(如2023-2024-1)学号(如:20231300)《计算机基础与程序设计》第X周学习总结作业信息这个作业属于哪个课程https://edu.cnblogs.com/campus/besti/2023-2024-1-CFAP/(如2022-2023-1-计算机基础与程序设计)这个作业要求在哪里https://www.cnblogs.com/rocedu/p/9577842.ht......
  • 二叉树的前序、中序、后序、层序遍历
    在写遍历函数前,我们需要知道这几种遍历方法的访问结点的顺序。前序遍历:1.先访问根节点。2.再访问左子树。3.最后访问右子树。中序遍历:1.先访问左子树。2.在访问根结点。3.最后访问右子树。后序遍历:1.先访问左子树。2.在访问右子树。3.最后访问根结点。层序遍历:按照......
  • KubeSphere 社区双周报 | KubeSphere 3.4.1 发布 | 2023.10.27-11.09
    KubeSphere社区双周报主要整理展示新增的贡献者名单和证书、新增的讲师证书以及两周内提交过commit的贡献者,并对近期重要的PR进行解析,同时还包含了线上/线下活动和布道推广等一系列社区动态。本次双周报涵盖时间为:2023.10.27-2023.11.09。贡献者名单新晋KubeSphereCon......
  • 2023-2024-1 20211327 信息安全系统设计与实现 学习笔记9(必做)
    学习笔记9信号和中断Unix/Linux中的信号处理信号处理步骤与异常Linux中的IPC实践过程信号和中断“中断”是从I/O设备或协处理器发送到CPU的外部请求,它将CPU从正常执行转移到中断处理。“信号”是发送给进程的请求,将进程从正常执行转移到中断处理。中断的概念和机制......
  • 数据结构之树(树转化为二叉树也叫二叉化)
    说明对于将一般树结构转化为二叉树,使用的方法称为“Child-Sibling”(Leftmost-child-next-right-sibling)法则。步骤1.将节点的所有兄弟节点,用横线连接起来2.删掉所有与子节点间的链接,只保留与最左子节点的链接3.顺时针旋转45度 二叉树转化为多叉树与树转化为二叉树......
  • P2722 [USACO3.1] 总分 Score Inflation
    还是选与不选的问题,但是每个背包可以无限次选,所以这是个完全背包!#include<bits/stdc++.h>usingnamespacestd;constintN=2e4+10;intf[N],w[N],t[N];intmain(){ intn,m; cin>>n>>m; for(inti=1;i<=m;i++){ cin>>w[i]>>t[i]; } for(inti=1;i<=m;i+......
  • [题解] CF1327F AND Segments
    ANDSegments有\(m\)个限制\((l,r,x)\)。要计算满足以下条件的长度为\(n\)的序列\(a\)的数量:\(\foralli\in[1,n],0\lea_i<2^k\)。\(\foralli\in[1,m],a_{l_i}\operatorname{and}a_{l_i+1}\operatorname{and}\cdots\operatorname{and}a_{r......