java查找算法_003二叉树查找

来源:互联网 发布:市政工程师待遇知乎 编辑:程序博客网 时间:2024/05/01 16:28
package com.wzs;public class BTreeSearch {public static int Max = 10;public static int[] Data = { 15, 2, 13, 6, 17, 25, 37, 7, 3, 18 }; // 数据数组public static int Counter = 1;public static void main(String args[]) {int i; // 循环计数变量BNTreeArray BNTree = new BNTreeArray(); // 声明二叉树数组BNTree.TreeData[0] = Data[0];for (i = 1; i < Max; i++)BNTree.Create(Data[i]); // 建立二叉查找树int KeyValue = 25;// 调用二叉查找法if (BNTree.BinarySearch(KeyValue) > 0)// 输出查找次数System.out.println("Search Time = " + BNTree.BinarySearch(KeyValue));else// 输出没有找到数据System.out.println("No Found!!");}}class BNTreeArray {public static int MaxSize = 20;public static int[] TreeData = new int[MaxSize];public static int[] RightNode = new int[MaxSize];public static int[] LeftNode = new int[MaxSize];public BNTreeArray() {int i; // 循环计数变量for (i = 0; i < MaxSize; i++) {TreeData[i] = 0;RightNode[i] = -1;LeftNode[i] = -1;}}// ----------------------------------------------------// 建立二叉树// ----------------------------------------------------public void Create(int Data) {int i; // 循环计数变量int Level = 0; // 树的阶层数int Position = 0;for (i = 0; TreeData[i] != 0; i++);TreeData[i] = Data;while (true) // 寻找节点位置{// 判断是左子树或是右子树if (Data > TreeData[Level]) {// 右树是否有下一阶层if (RightNode[Level] != -1)Level = RightNode[Level];else {Position = -1; // 设定为右树break;}} else {// 左树是否有下一阶层if (LeftNode[Level] != -1)Level = LeftNode[Level];else {Position = 1; // 设定为左树break;}}}if (Position == 1) // 建立节点的左右连结LeftNode[Level] = i; // 连结左子树elseRightNode[Level] = i; // 连结右子树}// ---------------------------------------------------------// 二叉查找法// ---------------------------------------------------------public static int BinarySearch(int KeyValue) {int Pointer; // 现在的节点位置int Counter; // 查找次数Pointer = 0;Counter = 0;while (Pointer != -1) {Counter++;// 找到了欲寻找之节点if (TreeData[Pointer] == KeyValue)return Counter; // 传回查找次数else if (TreeData[Pointer] > KeyValue)Pointer = LeftNode[Pointer]; // 往左子树找elsePointer = RightNode[Pointer];// 往右子树找}return 0; // 该节点不在此二叉树中}}

原创粉丝点击