博客
关于我
按之字形顺序打印二叉树
阅读量:412 次
发布时间:2019-03-06

本文共 1233 字,大约阅读时间需要 4 分钟。

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

解题思路

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

import java.util.ArrayList;import java.util.Stack;public class Solution {    public ArrayList
> Print(TreeNode pRoot) { // 用来存放结点 ArrayList
> list = new ArrayList<>(); if(pRoot == null) { return list; } // 判断奇偶层 int layer = 1; // 存放奇数层结点 Stack
s1 = new Stack<>(); // 存放偶数层结点 Stack
s2 = new Stack<>(); // 先把根结点放入奇数层 s1.push(pRoot); // 如果两个栈都为空,那么就证明所有结点都已遍历完毕 while(!s1.empty() || !s2.empty()) { // 当前层是奇数层 if(layer % 2 != 0) { // 存放奇数层的结点 ArrayList
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
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; }}

转载地址:http://vwnkz.baihongyu.com/

你可能感兴趣的文章
Nginx多域名,多证书,多服务配置,实用版
查看>>
nginx如何实现图片防盗链
查看>>
Nginx学习总结(13)——Nginx 重要知识点回顾
查看>>
Nginx学习总结(14)——Nginx配置参数详细说明与整理
查看>>
nginx学习笔记002---Nginx代理配置_案例1_实现了对前端代码的方向代理_并且配置了后端api接口的访问地址
查看>>
Nginx安装与常见命令
查看>>
Nginx安装及配置详解
查看>>
nginx安装配置
查看>>
Nginx实战经验分享:从小白到专家的成长历程!
查看>>
Nginx实现反向代理负载均衡
查看>>
nginx实现负载均衡
查看>>
nginx常用命令及简单配置
查看>>
nginx开机启动脚本
查看>>
nginx异常:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf
查看>>
nginx总结及使用Docker创建nginx教程
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:128
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in usrlocalnginxconfnginx.conf128
查看>>
nginx日志分割并定期删除
查看>>
Nginx日志分析系统---ElasticStack(ELK)工作笔记001
查看>>
Nginx映射本地json文件,配置解决浏览器跨域问题,提供前端get请求模拟数据
查看>>