数据与算法的课程中,给出了二叉树三种遍历方式的实现代码但是没有给出其递归实现。本文给出迭代实现。
测试结果如下:
前序遍历递归实现:
96487
前序遍历迭代实现:
96487
中序遍历递归实现:
46789
中序遍历迭代实现:
46789
后序遍历递归实现:
47869
后序遍历迭代实现:
47869
Process finished with exit code 0
代码如下:
package AlgorithmTest; import java.util.Stack; /** * Created by dell on 2016/12/3. */ public class IterationGoThrough { public static void main(String[] args) { BinarySearchTree binarySearchTree = new BinarySearchTree(); binarySearchTree.insertNode(9); binarySearchTree.insertNode(6); binarySearchTree.insertNode(4); binarySearchTree.insertNode(8); binarySearchTree.insertNode(7); System.out.println("前序遍历递归实现:"); preorder(binarySearchTree.getRootNode()); System.out.println(); System.out.println("前序遍历迭代实现:"); preorderIteration(binarySearchTree.getRootNode()); System.out.println(); System.out.println("中序遍历递归实现:"); inorder(binarySearchTree.getRootNode()); System.out.println(); System.out.println("中序遍历迭代实现:"); inorderIteration(binarySearchTree.getRootNode()); System.out.println(); System.out.println("后序遍历递归实现:"); postOrder(binarySearchTree.getRootNode()); System.out.println(); System.out.println("后序遍历迭代实现:"); postOrderIteration(binarySearchTree.getRootNode()); } //前序遍历 递归实现 public static void preorder(Node root){ if (root != null){ System.out.print(root.val); preorder(root.nodeLeft); preorder(root.nodeRight); } } //前序遍历 迭代实现 public static void preorderIteration(Node root){ Stack<Node> nodes = new Stack<>(); nodes.push(root); while (!nodes.isEmpty()){ root = nodes.pop(); if (root != null){ System.out.print(root.val); nodes.push(root.nodeRight); nodes.push(root.nodeLeft); } } } //中序遍历 递归实现 public static void inorder(Node root){ if (root != null){ inorder(root.nodeLeft); System.out.print(root.val); inorder(root.nodeRight); } } static class Pair{ Node node; int loction; public Pair(Node node, int loction) { this.node = node; this.loction = loction; } } //中序遍历 迭代实现 public static void inorderIteration(Node root){ Stack<Pair> stack = new Stack<>(); stack.push(new Pair(root, 1)); while (!stack.isEmpty()){ Pair pair = stack.peek(); root = pair.node; stack.pop(); if (root != null){ switch (pair.loction){ case 1: stack.push(new Pair(root, 2)); stack.push(new Pair(root.nodeLeft, 1)); break; case 2: System.out.print(root.val); stack.push(new Pair(root, 3)); stack.push(new Pair(root.nodeRight, 1)); break; case 3: break; } } } } //后序遍历 递归实现 public static void postOrder(Node root){ if (root != null){ postOrder(root.nodeLeft); postOrder(root.nodeRight); System.out.print(root.val); } } //中序遍历 迭代实现 public static void postOrderIteration(Node root){ Stack<Pair> stack = new Stack<>(); stack.push(new Pair(root, 1)); while (!stack.isEmpty()){ Pair pair = stack.peek(); root = pair.node; stack.pop(); if (root != null){ switch (pair.loction){ case 1: stack.push(new Pair(root, 2)); stack.push(new Pair(root.nodeLeft, 1)); break; case 2: stack.push(new Pair(root, 3)); stack.push(new Pair(root.nodeRight, 1)); break; case 3: System.out.print(root.val); break; } } } } }