二叉树的遍历(递归与非递归)
来源:互联网 发布:媒介数据分析经理招聘 编辑:程序博客网 时间:2024/06/05 04:16
package TreeNodePack;import java.util.Stack;public class BinTree { private char date; private BinTree lchild; private BinTree rchild; public BinTree(char c){ date=c; } //先序遍历,递归 public static void preOrder(BinTree t){ if(t==null){ return; } System.out.print(t.date); preOrder(t.lchild); preOrder(t.rchild); } //中序遍历递归 public static void InOrder(BinTree t){ if(t==null){ return; } InOrder(t.lchild); System.out.println(t.date); InOrder(t.rchild); } //后续遍历递归 public static void PostOrder(BinTree t){ if(t==null){ return; } PostOrder(t.lchild); PostOrder(t.rchild); System.out.println(t.date); } //先序遍历非递归 public static void PreOrder2(BinTree t){ Stack<BinTree>s=new Stack<BinTree>(); while(t!=null||!s.empty()){ while(t!=null){ System.out.println(t.date); s.push(t);//使用Stack存储t是为了找到节点的右子树 t=t.lchild; } if(!s.empty()){ t=s.pop(); t=t.rchild; } } } //中序遍历非递归 public static void InOrder2(BinTree t){ Stack<BinTree>s=new Stack<BinTree>(); while(t!=null||!s.isEmpty()){ while(t!=null){ s.push(t); t=t.lchild; } if(!s.isEmpty()){ t=s.pop(); System.out.println(t.date); t=t.rchild; } } } //后续遍历非递归 public static void PostOrder2(BinTree t){ Stack<BinTree>s=new Stack<BinTree>(); Stack<Integer>flag=new Stack<Integer>(); Integer i=new Integer(1);//设置一个右子树访问标志位,表示节点t的右子树是否访问,1表示访问过,0表示没有访问过 while(t!=null||!s.isEmpty()){ while(t!=null){//对于节点t,当节点t不为空时,把节点t入栈s,同时其右子树的访问标志位为0,将其入栈flag s.push(t); flag.push(new Integer(0)); t=t.lchild; } while(!s.isEmpty()&&flag.peek().equals(i)){//假如一个节点的右子树访问标志位等于1,表示该节点的右子树已经访问过 flag.pop();//把flag栈中的该节点的标志位取出 System.out.println(s.pop().date);//打印该节点 } if(!s.empty()){//假如一个节点的右子树访问标志位等于0表示该节点的右子树没有访问过 flag.pop();//将原来的0取出 flag.push(new Integer(i));//放入1 t=s.peek();//取s栈顶的元素,但是不改变栈s,注意不能用pop(),因为此时该节点还没有输出 t=t.rchild; } } } public static void main(String[] args) { BinTree b1=new BinTree('a'); BinTree b2=new BinTree('b'); BinTree b3=new BinTree('c'); BinTree b4=new BinTree('d'); BinTree b5=new BinTree('e'); b1.lchild=b2; b1.rchild=b3; b2.lchild=b4; b2.rchild=b5; System.out.println("前序遍历"); BinTree.PreOrder2(b1); System.out.println("中序遍历"); BinTree.InOrder2(b1); System.out.println("后序遍历"); BinTree.PostOrder2(b1); }}
0 0
- 二叉树的遍历(递归与非递归)
- 二叉树的遍历算法(递归与非递归)
- 二叉树的遍历(递归与非递归)
- 二叉树的遍历(递归与非递归)
- 二叉树的遍历(递归与非递归)
- 二叉树的遍历(递归与非递归)
- 二叉树的遍历(递归与非递归)
- 二叉树的遍历(递归与非递归)
- 【数据结构】二叉树的遍历(递归与非递归)
- 二叉树的遍历(递归与非递归)
- 二叉树的递归遍历与非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的递归遍历与非递归遍历
- lighttpd源代码分析资料
- 从“懒”心理去设计的常用功能
- shell大数据计算——bc巧用
- Pid控制算法—算法原理
- centos6.3
- 二叉树的遍历(递归与非递归)
- 办公软件的选择
- iOS开发:一个快速生成model属性的方法
- maven 上传jar到私服 pom 以及命令的方式
- U盘安装centos 6.3教程(超级详细图解教程)
- mysql配置详解
- 非root搭建lamp & 安装wordpress
- kill 信号
- 第八届河南省赛题最小换乘_NYOJ1238