class MyBinaryTree<T> { BinaryNode<T> root; public MyBinaryTree() { root = new BinaryNode<>(); } /** * 堆栈进行先序遍历 * * @param ts */ public void preorderTraversal(T... ts) { Stack<BinaryNode<T>> binaryStack = new Stack<>(); BinaryNode<T> temp = root; while (!binaryStack.isEmpty() || temp != null) { if (temp != null) { // 处理 System.out.println(temp.data); // 先序 if (temp != null) { binaryStack.push(temp); } temp = temp.left; } else { temp = binaryStack.pop(); temp = temp.right != null ? temp.right : null; } } } /** * 堆栈中序遍历 * * @param ts */ public void inorderTraversal(T... ts) { Stack<BinaryNode<T>> binaryStack = new Stack<>(); BinaryNode<T> temp = root; while (!binaryStack.isEmpty() || temp != null) { if (temp != null) { binaryStack.push(temp); temp = temp.left; } else { temp = binaryStack.pop(); // 处理 System.out.println(temp.data); temp = temp.right != null ? temp.right : null; } } } /** * 堆栈后序遍历 * * @param ts */ public void postorderTraversal(T... ts) { Stack<BinaryNode<T>> binaryStack = new Stack<>(); BinaryNode<T> temp = root; BinaryNode<T> node = null; while (!binaryStack.isEmpty() || temp != null) { if (temp != null) { binaryStack.push(temp); temp = temp.left; } else { temp = binaryStack.pop(); if (temp.right == null || temp.right == node) { // 处理 System.out.println(temp.data); node = temp; temp = null; } else { binaryStack.push(temp); temp = temp.right; binaryStack.push(temp); temp = temp.left; } } } } /** * 层级遍历 */ public void levelTraversal() { BinaryNode<T> temp = root; Queue<BinaryNode<T>> queue = new LinkedList<>(); queue.add(temp); while(!queue.isEmpty()) { temp = queue.poll();
// 处理 System.out.println(temp.data); if(temp.left!=null) { queue.add(temp.left); } if(temp.right!=null) { queue.add(temp.right); } } } } class BinaryNode<T> { BinaryNode<T> left; T data; BinaryNode<T> right; public BinaryNode() { } public BinaryNode(BinaryNode<T> left, T data, BinaryNode<T> right) { this.left = left; this.data = data; this.right = right; } }
测试代码:
private MyBinaryTree<String> binaryTree; @Before public void setUp() { binaryTree = new MyBinaryTree<>(); binaryTree.root.data = "A"; binaryTree.root.left = new BinaryNode<>(new BinaryNode<>(null, "D", null), "B", null); binaryTree.root.right = new BinaryNode<>(new BinaryNode<>(null, "F", null), "C", new BinaryNode<>(null, "E", null)); } @Test public void preorderTest() { binaryTree.preorderTraversal(); System.out.println("---------------先序遍历------------------"); } @Test public void inorderTest() { binaryTree.inorderTraversal(); System.out.println("---------------中序遍历------------------"); } @Test public void postorderTest() { binaryTree.postorderTraversal(); System.out.println("---------------后序遍历------------------"); } @Test public void levelTest() { binaryTree.levelTraversal(); System.out.println("---------------层级遍历------------------"); }