BST大小为n的二进制搜索树递归插入

时间:2019-03-15 18:10:49

标签: java

这是一个编程项目,我需要一些帮助。我正在尝试实现一个递归插入方法,以在二进制搜索树中重复插入n个随机选择的数字并收集高度h。我有一个Insert方法和getHeight方法,但是,我在驱动程序方法上苦苦挣扎。我可以到达创建随机整数p的地步,但是我需要朝正确的方向推,以创建节点z并设置z.key = p

//Node class
public class Node {

private Node leftChild;
private Node rightChild;
private Node parent;
private int  key;

public Node(int key) {

    this.key = key;
}

public Node getLeftChild() {
    return leftChild;
}

public void setLeftChild(Node leftChild) {
    this.leftChild = leftChild;
}

public Node getRightChild() {
    return rightChild;
}

public void setRightChild(Node rightChild) {
    this.rightChild = rightChild;
}

public Node getParent() {
    return parent;
}

public void setParent(Node parent) {
    this.parent = parent;
}

public void setKey(int key) {

    this.key = key;
}

public int getKey() {
    return key;
}

}

//Binary Search Tree Class
import java.util.Random;

public class BinarySearchTree {

private Node root;

public BinarySearchTree() {
    this.root = null;
}

public BinarySearchTree(Node root) {
    this.root = root;
}

public void insert(Node x) {
    Node y = null;
    Node z = root;
    while (z != null) {
        y = z;
        if (x.getKey() <= z.getKey()) {
            z = z.getLeftChild();
        } else {
            z = z.getRightChild();
        }
    }
    x.setParent(y);
    if (root == null) {
        root = x;
    } else if (x.getKey() <= y.getKey()) {
        y.setLeftChild(x);
    } else {
        y.setRightChild(x);
    }
}

public int getHeight(Node x) {
    if (x == null) {
        return 0;
    }
    int left = 0;
    int right = 0;
    if (x.getLeftChild() != null) {
        left = getHeight(x.getLeftChild()) + 1;
    }
    if (x.getRightChild() != null) {
        right = getHeight(x.getRightChild()) + 1;
    }
    return Math.max(left, right);
}

public Node getRoot() {
    return this.root;
}

public static void main(String[] args) {
    collectData();
}
public static void collectData() {

    int max = 10000;
    int min = 250;

    for (int n = min; n <= max; n += 250) {
        int sum_height = 0;
        for (int j = 1; j <= 10; j++) { //Take 10 measurements mj for j=1 to 10
            for (int i = 1; i <= n; i++) { //for i = 1 to n
                Random r = new Random(); //pick randomly a number p in the range [0,n]
                int p = r.nextInt((max - min) + 1) + min;
                BinarySearchTree b1 = new BinarySearchTree();
                /*
                I need help here...
                create a node z
                set z.key = p
                Tree-Insert(T,z)
                Measure the height hj of the tree
                Discard Tree
                sum_height += hj
                collect Height(n)= sum_heightn/10 // Average height for n
                 */

            }
        }
    }
}

}

0 个答案:

没有答案