树的初始化:(自己根据代码树的初始化画一个二叉树)
代码中的树的前序遍历:0 4 2 1 3 5 6 7
中序遍历:1 2 4 3 0 6 5 7
后序遍历:1 2 3 4 6 7 5 0
代码:
package Tree; import Stack.Stack; public class Demo2 { //树的非递归的前序,中序,后序的遍历 public static void main(String[] args) { Tree t1 = new Tree(1,null,null); Tree t2 = new Tree(2, t1, null); Tree t3 = new Tree(3, null, null); Tree t4 = new Tree(4, t2, t3); Tree t51 = new Tree(6,null,null); Tree t52 = new Tree(7, null, null); Tree t5 = new Tree(5, t51, t52); Tree t6 = new Tree(0, t4, t5); System.out.println("前序遍历(非递归)"); Demo2.PretraverseS(t6); System.out.println(); System.out.println("中序遍历(非递归)"); Demo2.IntraverseS(t6); System.out.println(); System.out.println("后续遍历(非递归):"); Demo2.PostraverseS(t6); } //前序遍历(非递归) public static void PretraverseS(Tree h){ if(h==null)return; Stack stack = new Stack(); stack.push(h); while(!stack.isEmpty()){ h = (Tree) stack.pop(); h.visit(); if(h.right!=null)stack.push(h.right); if(h.left!=null)stack.push(h.left); } } //中序遍历(非递归) public static void IntraverseS(Tree h){ if(h==null)return; Stack stack = new Stack(); while(h!=null||!stack.isEmpty()){ if(h!=null){ stack.push(h); h = h.left; }else { h = (Tree) stack.pop(); h.visit(); h = h.right; } } } //后序遍历(非递归) public static void PostraverseS(Tree h){ if(h==null)return; Stack stack = new Stack(); while(h!=null||!stack.isEmpty()){ if(h!=null){ stack.push(h); stack.push(1); h = h.left; }else{ while(!stack.isEmpty()){ int sign = (Integer) stack.pop(); h = (Tree) stack.pop(); if(sign==1){ stack.push(h); stack.push(2); h = h.right; break; }else{ h.visit(); h = null; } } } } } public static class Tree{ int val; Tree left; Tree right; public Tree(int val,Tree left,Tree right){ this.val = val; this.left = left; this.right = right; } public Tree(){} public void visit(){ System.out.print(val+" "); } } }