最近总结了下,二叉树的遍历的非递归实现过程,以下是整个java实现过程
package com.test.dayumianshi; import java.util.*; public class BinaryTreeRank { //存储除根结点所有节点的集合 private static List<Node> list = new ArrayList<Node>(); private static Node root; static class Node{ private int data; private Node left; private Node right; } //通过构造函数初始化根结点 public BinaryTreeRank(Node node){ node.data = 9; } //构造二叉树 static BinaryTreeRank structureBinaryTree(){ root = new BinaryTreeRank.Node(); BinaryTreeRank binaryTree = new BinaryTreeRank(root); for(int i=0;i<6;i++){ Node node = new Node(); switch (i){ case 0: node.data=7; root.left = node; list.add(node); break; case 1: node.data=10; root.right = node; list.add(node); break; case 2: node.data = 5; list.get(0).left = node; list.add(node); break; case 3: node.data = 8; list.get(0).right = node; list.add(node); break; case 4: node.data = 11; list.get(1).right = node; list.add(node); break; case 5: node.data = 3; list.get(2).left = node; list.add(node); break; } } return binaryTree; } //中序遍历 static void middleTravelWithoutRecursion(Node root){ System.out.print("中序遍历:\t"); Stack<Node> stack = new Stack<Node>(); Node node = root; while(node!=null||stack.size()>0){ while(node!=null){ stack.push(node); node = node.left; } node = stack.pop(); System.out.print(node.data+"\t"); node = node.right; } } //前序遍历 static void beforeTravelWithoutRecursion(Node root){ System.out.print("\n前序遍历:\t"); Stack<Node> stack = new Stack<Node>(); Node node = root; while(node!=null||!stack.isEmpty()){ while(node!=null){ stack.push(node); System.out.print(node.data+"\t"); node = node.left; } node = stack.pop(); node = node.right; } } //后序遍历 static void afterTravelWithoutRecursion(Node root){ System.out.print("\n后序遍历:\t"); Stack<Node> stack = new Stack<Node>(); Node node = root; while(true){ if(node!=null){ stack.push(node); node = node.left; }else{ if(stack.isEmpty()){ break; } if(null==stack.lastElement().right){ node = stack.pop(); System.out.print(node.data+"\t"); while(node == stack.lastElement().right){ System.out.print(stack.lastElement().data+"\t"); node = stack.pop(); if(stack.isEmpty()){ break; } } } if(!stack.isEmpty()){ node = stack.lastElement().right; }else{ node = null; //用于处理最后一个节点 } } } } public static void main(String[] args){ structureBinaryTree(); middleTravelWithoutRecursion(root); beforeTravelWithoutRecursion(root); afterTravelWithoutRecursion(root); } }