我正在创建一个二叉搜索树delete node方法,到目前为止,我有一个查找max和min的方法,还有insert方法。
你能给我一个大概的算法吗。。。
这是我目前的工作
public class BST {
private Node root; //first node top of the tree
public void insert(int key){
Node newNode = new Node (key);
if(root == null){ //check node, no tree yet
root = newNode; //give the tree a node
}
else {
Node current = root; //assigned root as current
Node parent;
while(true) {
parent = current;
if (key < current.key) {
current = current.leftChild;
if(current == null) {
parent.leftChild = newNode;
return;
}
} else {
current = current.rightChild;
if(current == null) {
parent.rightChild = newNode;
return;}
}
}
}
}
public Node findMin(){
Node current = root; //assigned root as current
Node last = null;
while(current != null) {
last = current;
current = current.leftChild;
}
return last;
}
public Node findMax() {
Node current = root;
Node last = null;
while(current != null) {
last = current;
current = current.rightChild;
}
return last;
}
}
public class Node {
int key;
Node leftChild, rightChild;
public Node(int key){
super();
this.key = key;
}
}
public class BSTApp {
public static void main (String args[]){
BST tree = new BST();
tree.insert(10);
tree.insert(15);
tree.insert(100);
tree.insert(88);
tree.insert(2);
System.out.println(tree.findMin().key); //Search for Min in BST
System.out.println(tree.findMax().key); //Search for Min in BST
}
}
我正在努力推进我的研究,这样我就能在数据结构和算法方面取得进展。我希望你们都能帮助我。
2条答案
按热度按时间hof1towb1#
wljmcqd82#