1. 程式人生 > 其它 >二叉樹-[先中後序 廣度深度優先]

二叉樹-[先中後序 廣度深度優先]

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); } } } }