33 二叉排序樹

2022-09-18 09:12:51 字數 2640 閱讀 8736

class node 

//查詢要刪除的結點

/***

* @param value 希望刪除的結點的值

* @return 如果找到返回該結點,否則返回null

*/public node search(int value) else if(value < this.value)

return this.left.search(value);

} else

return this.right.search(value);}}

//查詢要刪除結點的父結點

/***

* @param value 要找到的結點的值

* @return 返回的是要刪除的結點的父結點,如果沒有就返回null

*/public node searchparent(int value) else else if (value >= this.value && this.right != null) else }}

@override

public string tostring()

//新增結點的方法

//遞迴的形式新增結點,注意需要滿足二叉排序樹的要求

public void add(node node)

//判斷傳入的結點的值,和當前子樹的根結點的值關係

if(node.value < this.value) else

} else else }}

//中序遍歷

public void infixorder()

system.out.println(this);

if(this.right != null)

}

private node root;

public node getroot()

public node search(int value)  else 

}

public node searchparent(int value)  else 

}

public int delrighttreemin(node node) 

//這時 target就指向了最小結點

//刪除最小結點

delnode(target.value);

return target.value;

}

public void delnode(int value) else 

//如果我們發現當前這顆二叉排序樹只有乙個結點

if(root.left == null && root.right == null)

//去找到targetnode的父結點

node parent = searchparent(value);

//如果要刪除的結點是葉子結點

if(targetnode.left == null && targetnode.right == null) else if (parent.right != null && parent.right.value == value)

} else if (targetnode.left != null && targetnode.right != null) else else

} else

} else else

} else }}

}}

public void add(node node)  else 

}

public void infixorder()  else 

}

public static void main(string args) ;

binarysorttree binarysorttree = new binarysorttree();

//迴圈的新增結點到二叉排序樹

for (int j : arr)

//中序遍歷二叉排序樹

system.out.println("中序遍歷二叉排序樹~");

binarysorttree.infixorder(); // 1, 3, 5, 7, 9, 10, 12

//測試一下刪除葉子結點

binarysorttree.delnode(12);

binarysorttree.delnode(5);

binarysorttree.delnode(10);

binarysorttree.delnode(2);

binarysorttree.delnode(3);

binarysorttree.delnode(9);

binarysorttree.delnode(1);

binarysorttree.delnode(7);

system.out.println("root=" + binarysorttree.getroot());

system.out.println("刪除結點後");

binarysorttree.infixorder();

}

二叉排序樹

在複習資料結構,把這個東西總結一下。這種結構是動態查詢表,這種動態是相對靜態查詢 順序查詢,折半查詢,分塊查詢等 來說的。對於各種靜態鍊錶,要達到查詢複雜度為o logn 必須要求有序 而要使插入刪除複雜度為o 1 必須是鍊錶儲存。動態查詢表就可以同時滿足這兩者。動態查詢表的特點是表結構本身在查詢過...

二叉排序樹

name 二叉排序樹相關操作 author unimen date 2011 10 8 13 14 21 刪除結點比較麻煩,總結如下 4大種情況 1 結點p無右孩子 將該點的左孩子變為其在雙親中的同位孩子 1 p為其雙親的左孩子時將其的左孩子變為雙親的左孩子 2 p為其雙親的右孩子時將其的左孩子變為...

二叉排序樹

include include include include struct tree node void insert node struct tree node int void pre order struct tree node void in order struct tree node ...