博客
关于我
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 递归查找父节点_MySQL递归查询树状表的子节点、父节点具体实现
查看>>
mysql 里对root及普通用户赋权及更改密码的一些命令
查看>>
Mysql 重置自增列的开始序号
查看>>
MySQL 高可用性之keepalived+mysql双主
查看>>
mysql-connector-java各种版本下载地址
查看>>
mysql-group_concat
查看>>
MySQL-【4】基本操作
查看>>
Mysql-丢失更新
查看>>
Mysql-事务阻塞
查看>>
Mysql-存储引擎
查看>>
mysql-开启慢查询&所有操作记录日志
查看>>
MySQL-数据目录
查看>>
MySQL-数据页的结构
查看>>
MySQL-架构篇
查看>>
MySQL-索引的分类(聚簇索引、二级索引、联合索引)
查看>>
Mysql-触发器及创建触发器失败原因
查看>>
MySQL-连接
查看>>
mysql-递归查询(二)
查看>>
MySQL5.1安装
查看>>