【Java】 剑指offer(32) 从上往下打印二叉树
本文参考自《剑指offer》一书,代码采用Java语言。
题目
(一)从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
(二)从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
(三)请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
思路
(一)不分行从上往下打印二叉树:该题即为对二叉树的层序遍历,结点满足先进先出的原则,采用队列。每从队列中取出头部结点并打印,若其有子结点,把子结点放入队列尾部,直到所有结点打印完毕。
- /*
- * 不分行从上往下打印二叉树
- */
- // 题目:从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
- public void printTree1(TreeNode root) {
- if (root == null)
- return;
- LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
- queue.offer(root);
- TreeNode node = null;
- while (queue.size()!=0) {
- node = queue.poll();
- System.out.print(node.val + " ");
- if (node.left != null)
- queue.offer(node.left);
- if (node.right != null)
- queue.offer(node.right);
- }
- System.out.println();
- }
(二)分行从上到下打印二叉树:同样使用队列,但比第一题增加两个变量:当前层结点数目pCount,下一层结点数目nextCount。根据当前层结点数目来打印当前层结点,同时计算下一层结点数目,之后令pCount等于nextCount,重复循环,直到打印完毕。
- /*
- * 分行从上到下打印二叉树
- */
- // 题目:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层
- // 打印到一行。
- public void printTree2(TreeNode root) {
- if (root == null)
- return;
- LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
- queue.offer(root);
- TreeNode node = null;
- int pCount = 0; //当前层结点数目
- int nextCount = 1; //下一层结点数目
- while (!queue.isEmpty()) {
- pCount = nextCount;
- nextCount = 0;
- //打印当前层数字,并计算下一层结点数目
- for (int i = 1; i <= pCount; i++) {
- node = queue.poll();
- System.out.print(node.val + " ");
- if (node.left != null) {
- queue.offer(node.left);
- nextCount++;
- }
- if (node.right != null) {
- queue.offer(node.right);
- nextCount++;
- }
- }
- System.out.println();
- }
- }
(三)之字形打印二叉树:
(1)自己开始想的方法:在(二)的基础上,多定义一个表示当前层数的变量level。每层结点不直接打印,放入一个数组中,根据此时的层数level的奇偶来决定正向还是反向打印数组。
- /*
- * 之字形打印二叉树
- */
- // 题目:请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺
- // 序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,
- // 其他行以此类推。
- /**
- * 自己开始想的方法,采用数组存储每层的数字,根据当前层数确定正反向打印数组
- */
- public void printTree3_1(TreeNode root) {
- if (root == null)
- return;
- LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
- queue.offer(root);
- TreeNode node = null;
- int pCount = 0; //当前层结点数目
- int nextCount = 1; //下一层结点数目
- int level=1; //层数
- int[] pNums=null; //用于存储当前层的数字
- while (!queue.isEmpty()) {
- pCount = nextCount;
- nextCount = 0;
- pNums=new int[pCount];
- //存储当前层数字,并计算下一层结点数目
- for (int i = 0; i < pCount; i++) {
- node = queue.poll();
- pNums[i]=node.val;
- if (node.left != null) {
- queue.offer(node.left);
- nextCount++;
- }
- if (node.right != null) {
- queue.offer(node.right);
- nextCount++;
- }
- }
- //根据当前层数确定正向或者反向打印数组
- if((level&1)!=0 ) {
- for(int i=0;i<pCount;i++) {
- System.out.print(pNums[i]+" ");
- }
- }else {
- for(int i=pCount-1;i>=0;i--) {
- System.out.print(pNums[i]+" ");
- }
- }
- level++;
- System.out.println();
- }
- }
(2)书中提供的方法:采用两个栈,对于不同层的结点,一个栈用于正向存储,一个栈用于逆向存储,打印出来就正好是相反方向。
- /**
- * 采用两个栈进行操作的方法
- */
- public void printTree3_2(TreeNode root) {
- if (root == null)
- return;
- Stack<TreeNode> stack1 = new Stack<TreeNode>();
- Stack<TreeNode> stack2 = new Stack<TreeNode>();
- TreeNode node = null;
- stack1.push(root);
- while(!stack1.empty() || !stack2.empty()) {
- while(!stack1.empty()) {
- node=stack1.pop();
- System.out.print(node.val + " ");
- if (node.left != null)
- stack2.push(node.left);
- if (node.right != null)
- stack2.push(node.right);
- }
- System.out.println();
- while(!stack2.empty()) {
- node=stack2.pop();
- System.out.print(node.val + " ");
- if (node.right != null)
- stack1.push(node.right);
- if (node.left != null)
- stack1.push(node.left);
- }
- System.out.println();
- }
- }
测试算例
1.功能测试(完全二叉树;左斜树;右斜树)
2.特殊测试(null;一个结点)
完整Java代码
含测试代码:
- import java.util.LinkedList;
- import java.util.Stack;
- /**
- *
- * @Description 面试题32:从上往下打印二叉树
- *
- * @author yongh
- */
- public class PrintTreeFromTopToBottom {
- public class TreeNode {
- int val = 0;
- TreeNode left = null;
- TreeNode right = null;
- public TreeNode(int val) {
- this.val = val;
- }
- }
- /*
- * 不分行从上往下打印二叉树
- */
- // 题目:从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
- public void printTree1(TreeNode root) {
- if (root == null)
- return;
- LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
- queue.offer(root);
- TreeNode node = null;
- while (queue.size()!=0) {
- node = queue.poll();
- System.out.print(node.val + " ");
- if (node.left != null)
- queue.offer(node.left);
- if (node.right != null)
- queue.offer(node.right);
- }
- System.out.println();
- }
- /*
- * 分行从上到下打印二叉树
- */
- // 题目:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层
- // 打印到一行。
- public void printTree2(TreeNode root) {
- if (root == null)
- return;
- LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
- queue.offer(root);
- TreeNode node = null;
- int pCount = 0; //当前层结点数目
- int nextCount = 1; //下一层结点数目
- while (!queue.isEmpty()) {
- pCount = nextCount;
- nextCount = 0;
- //打印当前层数字,并计算下一层结点数目
- for (int i = 1; i <= pCount; i++) {
- node = queue.poll();
- System.out.print(node.val + " ");
- if (node.left != null) {
- queue.offer(node.left);
- nextCount++;
- }
- if (node.right != null) {
- queue.offer(node.right);
- nextCount++;
- }
- }
- System.out.println();
- }
- }
- /*
- * 之字形打印二叉树
- */
- // 题目:请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺
- // 序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,
- // 其他行以此类推。
- /**
- * 自己开始想的方法,采用数组存储每层的数字,根据当前层数确定正反向打印数组
- */
- public void printTree3_1(TreeNode root) {
- if (root == null)
- return;
- LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
- queue.offer(root);
- TreeNode node = null;
- int pCount = 0; //当前层结点数目
- int nextCount = 1; //下一层结点数目
- int level=1; //层数
- int[] pNums=null; //用于存储当前层的数字
- while (!queue.isEmpty()) {
- pCount = nextCount;
- nextCount = 0;
- pNums=new int[pCount];
- //存储当前层数字,并计算下一层结点数目
- for (int i = 0; i < pCount; i++) {
- node = queue.poll();
- pNums[i]=node.val;
- if (node.left != null) {
- queue.offer(node.left);
- nextCount++;
- }
- if (node.right != null) {
- queue.offer(node.right);
- nextCount++;
- }
- }
- //根据当前层数确定正向或者反向打印数组
- if((level&1)!=0 ) {
- for(int i=0;i<pCount;i++) {
- System.out.print(pNums[i]+" ");
- }
- }else {
- for(int i=pCount-1;i>=0;i--) {
- System.out.print(pNums[i]+" ");
- }
- }
- level++;
- System.out.println();
- }
- }
- /**
- * 采用两个栈进行操作的方法
- */
- public void printTree3_2(TreeNode root) {
- if (root == null)
- return;
- Stack<TreeNode> stack1 = new Stack<TreeNode>();
- Stack<TreeNode> stack2 = new Stack<TreeNode>();
- TreeNode node = null;
- stack1.push(root);
- while(!stack1.empty() || !stack2.empty()) {
- while(!stack1.empty()) {
- node=stack1.pop();
- System.out.print(node.val + " ");
- if (node.left != null)
- stack2.push(node.left);
- if (node.right != null)
- stack2.push(node.right);
- }
- System.out.println();
- while(!stack2.empty()) {
- node=stack2.pop();
- System.out.print(node.val + " ");
- if (node.right != null)
- stack1.push(node.right);
- if (node.left != null)
- stack1.push(node.left);
- }
- System.out.println();
- }
- }
- //============测试代码==============
- private void test(int testNum,TreeNode root) {
- System.out.println("=========test"+testNum+"===========");
- System.out.println("method1:");
- printTree1(root);
- System.out.println("method2:");
- printTree2(root);
- System.out.println("method3_1:");
- printTree3_1(root);
- System.out.println("method3_2:");
- printTree3_2(root);
- }
- //null
- private void test1() {
- TreeNode node=null;
- test(1, node);
- }
- //单个结点
- private void test2() {
- TreeNode node=new TreeNode(1);
- test(2, node);
- }
- //左斜
- private void test3() {
- TreeNode node1=new TreeNode(1);
- TreeNode node2=new TreeNode(2);
- TreeNode node3=new TreeNode(3);
- node1.left=node2;
- node2.left=node3;
- test(3, node1);
- }
- //右斜
- private void test4() {
- TreeNode node1=new TreeNode(1);
- TreeNode node2=new TreeNode(2);
- TreeNode node3=new TreeNode(3);
- node1.right=node2;
- node2.right=node3;
- test(4, node1);
- }
- //完全二叉树
- private void test5() {
- TreeNode[] nodes = new TreeNode[15];
- for(int i=0;i<15;i++) {
- nodes[i]= new TreeNode(i+1);
- }
- for(int i=0;i<7;i++) {
- nodes[i].left=nodes[2*i+1];
- nodes[i].right=nodes[2*i+2];
- }
- test(5, nodes[0]);
- }
- public static void main(String[] args) {
- PrintTreeFromTopToBottom demo= new PrintTreeFromTopToBottom();
- demo.test1();
- demo.test2();
- demo.test3();
- demo.test4();
- demo.test5();
- }
- }
- =========test1===========
- method1:
- method2:
- method3_1:
- method3_2:
- =========test2===========
- method1:
- method2:
- method3_1:
- method3_2:
- =========test3===========
- method1:
- method2:
- method3_1:
- method3_2:
- =========test4===========
- method1:
- method2:
- method3_1:
- method3_2:
- =========test5===========
- method1:
- method2:
- method3_1:
- method3_2:
PrintTreeFromTopToBottom
收获
1.层序遍历时,一般都要用到队列,可以用LinkedList类(方法:poll() 和 offer(Obj) )。
2.在分行打印时,定义的两个int有明显实际意义(当前层结点数目,下一层结点数目)。自己编程时,一开始只知道要设置两个变量,但没有去想这两个变量的实际意义。当明白变量意义时,自己的思路会更清晰,而且代码可读性也更好。
【Java】 剑指offer(32) 从上往下打印二叉树的更多相关文章
- 剑指offer——32从上到下打印二叉树
题目描述 从上往下打印出二叉树的每个节点,同层节点从左至右打印. 题解: 就是简单的层序遍历 class Solution { public: vector<int> PrintFro ...
- 《剑指offer》从上往下打印二叉树
本题来自<剑指offer> 从上往下打印二叉树 题目: 从上往下打印出二叉树的每个节点,同层节点从左至右打印. 思路: 队列的思想. 先将根节点加入,当取该节点时候,依次将左右子树加入,直 ...
- 【剑指Offer】从上往下打印二叉树 解题报告(Python)
[剑指Offer]从上往下打印二叉树 解题报告(Python) 标签(空格分隔): 剑指Offer 题目地址:https://www.nowcoder.com/ta/coding-interviews ...
- 剑指offer系列20--从上到下打印二叉树
* 20 [题目]从上往下打印出二叉树的每个节点,同层节点从左至右打印. * [思路]从根结点开始,先保存结点,再看根结点的左右结点有没有值. * 有,就将左右值放到集合中: * 根节点输出后,打印根 ...
- 剑指Offer 22. 从上往下打印二叉树 (二叉树)
题目描述 从上往下打印出二叉树的每个节点,同层节点从左至右打印. 题目地址 https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed25 ...
- 【剑指offer】从上向下打印二叉树
转载请注明出处:http://blog.csdn.net/ns_code/article/details/26089165 剑指offer上的第23题,实际上就是考察二叉树的层序遍历,详细思想能够參考 ...
- Go语言实现:【剑指offer】从上往下打印二叉树
该题目来源于牛客网<剑指offer>专题. 从上往下打印出二叉树的每个节点,同层节点从左至右打印. 不需分层,一维数组. Go语言实现: /** * Definition for a bi ...
- 剑指OFFER之从上往下打印二叉树(九度OJ1523)
题目描述: 从上往下打印出二叉树的每个节点,同层节点从左至右打印. 输入: 输入可能包含多个测试样例,输入以EOF结束.对于每个测试案例,输入的第一行一个整数n(1<=n<=1000, : ...
- 剑指offer:从上往下打印二叉树
题目描述: 从上往下打印出二叉树的每个节点,同层节点从左至右打印. 解题思路: 实际就是二叉树的中序遍历问题.之前在leetcode刷过类似题目. 利用队列完成即可. 代码: /* struct Tr ...
随机推荐
- 攻击WEP加密无线网络
1.介绍 针对客户端环境和无客户端环境下破解WEP的几类方法. 有客户端环境: 一般当前无线网络中存在活动的无线客户端环境,即有用户通过无线连接到无线AP上并正在进行上网等操作时. 无客户端环境: 1 ...
- VS中空项目、win32项目、控制台程序的区别(转)
空项目,大多数想单纯创建c++工程的新同学,打开vs后很可能不知道选择创建什么工程,这时候请相信我,空项目是你最好的选择.因为空工程不包含任何的源代码文件,接下来你只需要在相应的源代码文件夹和头文件文 ...
- Linux常用命令(一)查看日志
当日志文件存储很大时,需要Linux命令查看: Log 在目录 /var/log/ 下 常用命令: tail head grep sed cat tac https://blog.csdn.net ...
- mysql 原理 ~ sql执行
一 普通sql执行的具体过程1 连接器 管理连接,权限验证2 分析器 词法分析,语法分析 比如 数据表和数据列是否存在, 别名是否有歧义,是否符合标准sql语法等3 优化器检测 执行计划生 ...
- mongodb系列~mongo常用命令
mongodb常用命令大全1 索引相关命令 db.chenfeng.ensureIndex({"riqi":1}) 添加索引会阻塞nohup mongo --eval " ...
- mysql 原理 ~ checkpoint
一 简介:今天咱们来聊聊checkpoint 二 定义: checkpoin是重做日志对数据页刷新到磁盘的操作做的检查点,通过LSN号保存记录,作用是当发生宕机等crash情况时,再次启动时会查询ch ...
- 解决jdk1.7,1.8共存问题小思
一 起因 随着jdk1.9呼之欲出之势,准备花点时间把jdk1.8搞掉,于是准备下一个项目的依赖改为jdk1.8,先去下载安装,安装好之后电脑上就存在两个版本的jdk.然后将两个版本的jdk路径都配置 ...
- Java注解之Retention、Documented、Target、Inherited介绍
先看代码,后面一个个来解析: @Retention(RetentionPolicy.RUNTIME) @Target(value = {ElementType.METHOD, ElementType. ...
- BFGS算法(转载)
转载链接:http://blog.csdn.net/itplus/article/details/21897443 这里,式(2.38)暂时不知如何证出来,有哪位知道麻烦给个思路.
- [转]GDB-----2.watchpoint
TODO需要在ARM下验证 1. 前言 watchpoint,顾名思义,其一般用来观察某个变量/内存地址的状态(也可以是表达式),如可以监控该变量/内存值是否被程序读/写情况. 在gdb中可通过下面的 ...