二叉排序(查詢)樹的實現
阿新 • • 發佈:2018-12-13
二叉樹排序樹又稱二叉查詢數。它或者是一棵空數,或者是具有下列性質的二叉樹:
①如果左子樹不為空,那麼左子樹上所有節點的值均小於它的根節點的值;
②如果右子樹不為空,那麼右子樹上所有節點的值均大於其根節點的值;
③左右子樹也分別為二叉排序樹
實現方法:
package com.tongtong.tree; /** * 二叉樹的實現 */ public class BinaryTree { private Node root; public BinaryTree(){ root = null; } //將data插入到排序二叉樹中 public void insert(int data){ Node newNode = new Node(data); if(root == null){ root = newNode; }else{ Node current = root; Node parent; //各個主節點 while(true){ //尋找插入的位置 parent = current; if(data < current.data){ current = current.left; if(current == null){ parent.left = newNode; return; } }else{ current = current.right; if(current == null){ parent.right = newNode; return; } } } } } //將數值輸入構建二叉樹 public void buildTree(int[] data){ for(int i=0;i<data.length;i++){ insert(data[i]); } } //中序遍歷方法遞迴實現-->左根右 public void inOrder(Node localRoot){ if(localRoot != null){ inOrder(localRoot.left); System.out.print(localRoot.data + " "); inOrder(localRoot.right); } } public void inOrder(){ inOrder(this.root); } //前序遍歷方法遞迴實現-->根左右 public void preOrder(Node localRoot){ if(localRoot != null){ System.out.print(localRoot.data + " "); preOrder(localRoot.left); preOrder(localRoot.right); } } public void preOrder(){ preOrder(this.root); } //後序遍歷方法遞迴實現-->左右根 public void postOrder(Node localRoot){ if(localRoot != null){ postOrder(localRoot.left); postOrder(localRoot.right); System.out.print(localRoot.data + " "); } } public void postOrder(){ postOrder(this.root); } public static void main(String[] args) { BinaryTree biTree = new BinaryTree(); int[] data = {2,8,7,4,9,3,1,6,7,5}; biTree.buildTree(data); System.out.println("二叉樹的中序遍歷========"); biTree.inOrder(); System.out.println(); System.out.println("二叉樹的前序遍歷========"); biTree.preOrder(); System.out.println(); System.out.println("二叉樹的後序遍歷========"); biTree.postOrder(); } }