標籤:重複 stat sts com 構建 存在 node 尋找演算法 creat
package com.tree.find;public class TestSearchBST { private static class BiNode{ int data; BiNode lchild; BiNode rchild; } public static boolean hasBuild = false; public static void createBiTree(BiNode head, int array[]){ head.data = array[0]; BiNode next; for(int i=1;i<array.length;i++){ hasBuild = false; next = new BiNode(); next.data = array[i]; build(head,next); } } public static void build(BiNode t, BiNode next){ if(t != null){ if(t.data < next.data){ build(t.rchild, next); if(!hasBuild){ // 設定一個標量,如果結點已經構建進樹,之後就直接彈出,避免已經構建好的結點出現重複覆蓋的現象 t.rchild = next; hasBuild = true; } }else{ build(t.lchild,next); if(!hasBuild){ t.lchild = next; hasBuild = true; } } } } public static void forEach(BiNode t){ if(t != null){ //中序遍曆,可以從小到大排好序 forEach(t.lchild); System.out.println(t.data); forEach(t.rchild); } } //尋找 static boolean isFind = false; static BiNode findedNode = null; public static void searchBSF(BiNode t, int key){ if(t == null){ return; }else if(key == t.data){ findedNode = t; // 把找到的結點賦值給findedNode isFind = true; }else if(key < t.data){ searchBSF(t.lchild,key); }else{ searchBSF(t.rchild,key); } } //插入 public static void insertBSF(BiNode t,int key){ searchBSF(t,key); if(!isFind){//如果樹中不存在這個資料,就插入 BiNode n = new BiNode(); n.data = key; hasBuild = false; // 剛開始是沒有構建入樹的 build(t,n); } } public static void alert(BiNode t, int oldVal, int newVal){ searchBSF(t,oldVal); if(isFind){ findedNode.data = newVal; } } public static void main(String[] args) { BiNode t = new BiNode(); int arr[] = new int[]{23,63,76,45,12,78,89,44}; createBiTree(t,arr); //尋找資料是否存在// searchBSF(t,23);// System.out.println(isFind); //插入新資料// forEach(t);// insertBSF(t,50);// forEach(t); // forEach(t);// delete(t, 12);// System.out.println();// forEach(t); //searchBSF(t,23); //System.out.println(findedNode.data); //System.out.println(isFind); //修改操作// forEach(t);// alert(t, 23, 111);// forEach(t); }}
尋找演算法(二叉排序樹)