博客
关于我
java遍历二叉树
阅读量:202 次
发布时间:2019-02-28

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

1,问题分析

    

public void visitFirst(Node tree) {        if (tree != null) {            System.out.print(tree.value + " ");//访问语句            visitFirst(tree.left);            visitFirst(tree.right);        }    }

 

由于不论先序还是中序,后序,在程序运行流程上没有本质区别,区别仅仅是访问语句的执行时间点。所以,只要有了先序的程序流程,改变一下访问语句代码位置,就可以实现前三种遍历方式。

 

2,先序遍历(非递归)

public void visitFirst_N(Node tree) {        if (tree != null) {            Stack
s = new Stack(); Node cur = tree; s.push(cur); while (cur != null){ System.out.print(cur.value + " ");//访问语句代码 cur = cur.left; if (cur != null) s.push(cur); else { while(!s.empty()){ Node t=s.pop(); cur=t.right; if(cur!=null) { s.push(cur);break;} } } } } }

3,中序遍历(非递归)

public void midTest(Node tree){        if(tree!=null){           Stack
s=new Stack(); Node cur=tree; s.push(cur); while(cur!=null){ cur=cur.left; if(cur!=null){ s.push(cur); }else{ while(!s.empty()){ Node t=s.pop(); System.out.print(t.value+" ");//访问语句代码 cur=t.right; if(cur!=null){ s.push(cur); break; } } } } } }

4,后续遍历(非递归)

比较复杂,为保证程序流程,将左边pop出来的数据填回去!由于有内存大小限制,不能使用标记数组!

public void LastTest(Node tree) {        if (tree != null) {            Stack
s = new Stack(); Node cur = tree; s.push(cur); while (cur != null) { cur = cur.left; if (cur != null) { s.push(cur); } else { while (!s.empty()) { Node t = s.peek(); cur = t.right; if (cur == null) { Node x = s.pop(); System.out.print(x.value + " "); Node y = s.pop(); if (y.left == x) { s.push(y); cur = y.right; } else { Node k=s.peek(); System.out.print(y.value + " "); //清空栈 if(k.right==y) { while (!s.empty()) { System.out.print(s.pop().value + " "); } return;//直接结束 } cur = k.right; //调试 // Scanner sc = new Scanner(System.in); //sc.nextInt(); } } if (cur != null) { s.push(cur); break; } } } } } }

5,层次遍历(非递归)

private void visitLevel(Node x) {        Queue
queue = new Queue<>(); while (x != null) { System.out.print(x.value + " "); if (x.left != null) queue.enqueue(x.left); if (x.right != null) queue.push(x.right); x = queue.deQueue(); } }

 

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

你可能感兴趣的文章
MySQL原理、设计与应用全面解析
查看>>
MySQL原理简介—1.SQL的执行流程
查看>>
MySQL参数调优详解
查看>>
mysql参考触发条件_MySQL 5.0-触发器(参考)_mysql
查看>>
MySQL及navicat for mysql中文乱码
查看>>
MySqL双机热备份(二)--MysqL主-主复制实现
查看>>
MySQL各个版本区别及问题总结
查看>>
MySql各种查询
查看>>
mysql同主机下 复制一个数据库所有文件到另一个数据库
查看>>
mysql启动以后会自动关闭_驾照虽然是C1,一直是开自动挡的车,会不会以后就不会开手动了?...
查看>>
mysql启动和关闭外键约束的方法(FOREIGN_KEY_CHECKS)
查看>>
Mysql启动失败解决过程
查看>>
MySQL启动失败:Can't start server: Bind on TCP/IP port
查看>>
mysql启动报错
查看>>
mysql启动报错The server quit without updating PID file几种解决办法
查看>>
MySQL命令行登陆,远程登陆MySQL
查看>>
mysql命令:set sql_log_bin=on/off
查看>>
mySQL和Hive的区别
查看>>
MySQL和Java数据类型对应
查看>>
mysql和oorcale日期区间查询【含左右区间问题】
查看>>