正文之前
重温算法,今天看了下《算法导论》,二叉搜索树的内容,总算没有以前看的时候的那种晦涩感了。。。明天继续加油!!!今天大概用Java实现了下二叉搜索树的建立和输出,至于检索这个简单功能就不说了,插入功能也实现了。就差个删除了~emmm 明天上午搞完它!!!
这个是Java的《数据结构》
要电子书的可以找我。。。留下邮箱即可。。
正文
import java.util.Arrays;
import java.util.Random;
import java.util.LinkedList;
import java.util.Queue;
class node{
private int key;
node leftChild;
node rightChild;
node parent;
node(int x){
this.key=x;
}
node(){};
public node getLeftChild(){
return this.leftChild;
}
public node getRightChild(){
return this.rightChild;
}
public int getKey(){
return this.key;
}
public node getParent(){
return this.parent;
}
}
class Tree{
node head;
int size;
Tree(){this.size = 0;};
public node getHead(){
return this.head;
}
public void walk(Queue<String> queue,node par){
if(par.getLeftChild()!=null){
queue.add("* "+par.getLeftChild().getKey()+ " ");
walk(queue,par.getLeftChild());
}
if (par.getRightChild()!=null){
queue.add("* "+par.getRightChild().getKey() + " ");
walk(queue,par.getRightChild());
}
}
public String toString(){
System.out.print("输出树形: ");
Queue<String> queue = new LinkedList<>();
String out = "";
if (this.head!=null){
String one = "ok";
walk(queue,this.head);
while(one!=null) {
one = queue.poll();
if(one!=null)
out += one;
}
queue.add("* "+this.head.getKey()+"\n");
}
return out;
}
}
public class TestTree{
public static void insertSort(int []arr, int n){
for (int i = 1; i < n; ++i)
{
int e = arr[i];
int j=i;
for (; j > 0; --j)
{
if (e < arr[j-1])
arr[j] = arr[j-1];
else
break;
}
arr[j] = e;
}
}
public static void insertToTree(Tree tree,int x){
tree.size+=1;
node newnode = new node(x);
node tmp = tree.getHead();
if ( tmp==null)
tree.head = newnode;
while(tmp!=null) {
if (x < tmp.getKey()) {
if (tmp.getLeftChild()==null || x > tmp.getLeftChild().getKey()) {
newnode.parent = tmp;
newnode.leftChild = tmp.getLeftChild();
tmp.leftChild = newnode;
return;
}
else
tmp = tmp.getLeftChild();
}
else {
if ( tmp.getRightChild()==null || x > tmp.getRightChild().getKey()) {
newnode.parent = tmp;
newnode.rightChild = tmp.getRightChild();
tmp.rightChild = newnode;
return;
}
else
tmp = tmp.getRightChild();
}
}
}
public static Tree generateTree(int[] arr){
Tree tree = new Tree();
// insertSort(arr,arr.length);
int head = arr.length/2;
insertToTree(tree,arr[head]);
for (int i=0;i<arr.length;++i) {
if (i!=head) {
insertToTree(tree,arr[i]);
}
}
return tree;
}
public static void main(String[] args) {
Random rdm = new Random(System.currentTimeMillis());
int [] randomArr = new int[20];
for(int i=0;i<20;i++)
randomArr[i] = Math.abs(rdm.nextInt())%50 +1;
Tree tree = generateTree(randomArr);
System.out.println(Arrays.toString(randomArr));
System.out.println(tree.toString());
}
}
正文之后
溜了溜了~~~回去玩手机去!