二叉树-[先中后序 广度深度优先]
package com.tree; import java.util.LinkedList; import java.util.Stack; public class BSTree<T extends Comparable> { public static void main(String[] args) { BSTree<Integer> tree = new BSTree<>(); tree.add(16); tree.add(14); tree.add(8); tree.add(22); tree.add(67); tree.add(9); new TreePrinter().print(tree.root); // tree.preOrder(tree.root); // tree.order(tree.root); // tree.postOrder(tree.root); // 9 8 14 67 22 16 // tree.searchByBreadthFirst(tree.root); tree.searchByDeepFirst(tree.root); } /** * 先序:根左右 */ public void preOrder(BSTNode node) { if (node == null) { return; } System.out.print(node.data + " "); preOrder(node.left); preOrder(node.right); } /** * 中序:左根右 检验二叉树的方法(遍历元素是否有序) */ public void order(BSTNode node) { if (node == null) { return; } order(node.left); System.out.print(node.data + " "); order(node.right); } /** * 后序:左右根 */ public void postOrder(BSTNode node) { if (node == null) { return; } postOrder(node.left); postOrder(node.right); System.out.print(node.data + " "); } /** * 广度优先 * @param node */ public void searchByBreadthFirst(BSTNode node) { if (node == null) return; LinkedList<BSTNode> linkedList = new LinkedList<>(); linkedList.add(node); // 从末尾添加 while (!linkedList.isEmpty()) { BSTNode item = linkedList.remove(); // 从首部移除 System.out.print(item.data + " "); if (item.left != null) { linkedList.add(item.left); } if (item.right != null) { linkedList.add(item.right); } } } /** * 深度优先 * @param node */ public void searchByDeepFirst(BSTNode node) { if (node == null) return; Stack<BSTNode> stack = new Stack<>(); stack.push(node); while (!stack.isEmpty()) { BSTNode pop = stack.pop(); System.out.print(pop.data + " "); if (pop.right != null) { stack.push(pop.right); } if (pop.left != null) { stack.push(pop.left); } } } public void add(T data) { BSTNode<T> tNode = new BSTNode<>(data); if (this.root == null) { this.root = tNode; } else { add(this.root, tNode); } } private BSTNode<T> root; static class BSTNode<T> { BSTNode<T> left; BSTNode<T> right; T data; public BSTNode(T data) { this.data = data; } } private void add(BSTNode<T> node, BSTNode newNode) { if (node.data.compareTo(newNode.data) > 0) { if (node.left == null) { node.left = newNode; } else { add(node.left, newNode); } } else if (node.data.compareTo(newNode.data) < 0) { if (node.right == null) { node.right = newNode; } else { add(node.right, newNode); } } } }