java實現二叉樹查詢
阿新 • • 發佈:2022-04-17
java實現二叉樹查詢
節點類
/** * 節點類 */ class Node { private int id; private Node left; private Node right; /** * 前序查詢 * * @param id 需要被尋找的id */ public Node preSearch(int id) { // 判斷當前節點 if (this.id == id) { return this; } Node result = null; if (this.left != null) { result = this.left.preSearch(id); } if (result != null) { return result; } if (this.right != null) { result = this.right.preSearch(id); } return result; } /** * 中序查詢 * * @param id 同上 * @return 找到的節點 */ public Node infixSearch(int id) { Node result = null; if (this.left != null) { result = this.left.infixSearch(id); } if (result != null) { return result; } if (this.id == id) { return this; } if (this.right != null) { result = this.right.infixSearch(id); } return result; } /** * 後序查詢 * * @param id 同上 * @return */ public Node postSearch(int id) { Node result = null; if (this.left != null) { result = this.left.postSearch(id); } if (result != null) { return result; } if (this.right != null) { result = this.right.postSearch(id); } if (result != null) { return result; } if (this.id == id) { return this; } return result; } @Override public String toString() { return "Node{" + "id=" + id + '}'; } public Node(int id) { this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } }
二叉樹類
/** * 二叉樹 */ class BinaryTree { private Node root; /** * 前序查詢 */ public Node preSearch(int id) { if (this.root == null) { System.out.println("二叉樹為空"); return null; } return this.root.preSearch(id); } /** * 中序查詢 */ public Node infixSearch(int id) { if (this.root == null) { System.out.println("二叉樹為空"); return null; } return this.root.infixSearch(id); } /** * 後序查詢 */ public Node postSearch(int id) { if (this.root == null) { System.out.println("二叉樹為空"); return null; } return this.root.postSearch(id); } public void setRoot(Node root) { this.root = root; } }
測試類
public class SearchDemo { public static void main(String[] args) { BinaryTree binaryTree = new BinaryTree(); // 建立需要的節點 Node root = new Node(000); Node node01 = new Node(001); Node node02 = new Node(002); Node node03 = new Node(003); Node node04 = new Node(004); // 手動建立二叉樹 binaryTree.setRoot(root); root.setLeft(node01); root.setRight(node02); node02.setLeft(node03); node02.setRight(node04); Node node = binaryTree.preSearch(002); System.out.println(node); } }