How to create a binary search tree that includes all numbers from 1 to n

青春壹個敷衍的年華 提交于 2019-12-11 04:44:36

问题


Im trying to create a Binary search tree that includes all numbers from 1 to n. an example would be from 1 to 5 would be something like

root: 3

root.left: 2

root.left.left = 1

root.right = 4

root.right.right = 5

This tree happens to be not very balanced, but I would prefer a method that produces as balanced of a tree as possible.

I am trying to create my own data structure for this, so I basically just wrote a Node class:

    private class BinaryNode{
        int data;
        BinaryNode left;
        BinaryNode right;
        BinaryNode parent;
    }

And I planned on having that inside another class, which represents the tree itself. I am stuck finding a good way determine the left/right values appropriately to build the tree, any help is appreciated!


回答1:


The data on the root node would be (n+1)/2; if you've got a subtree representing the range [i..j], the root of that subtree is (i+j)/2 (using integer arithmetic).

You can build the tree recursively using that fact:

static BinaryNode build(int i, int j) {
    if (i > j) return null;

    int mid = (i + j) / 2;  // Assumes i >= 0.

    BinaryNode node = new BinaryNode();
    node.data = mid;

    node.left = build(i, mid - 1);
    if (node.left != null) node.left.parent = node;

    node.right = build(mid + 1, j);
    if (node.right != null) node.right.parent = node;

    return node;
}

Then start the recursive call:

BinaryNode node = build(1, n);

It must be pointed out, however, that such a binary search tree (storing contiguous integers from 1 to n) is useless: you may as well simply use an array, and "search" it using an array index.




回答2:


public void insert(int id){
    Node newNode = new Node(id);
    if(root==null){
        root = newNode;
        return;
    }
    Node current = root;
    Node parent = null;
    while(true){
        parent = current;
        if(id<current.data){                
            current = current.left;
            if(current==null){
                parent.left = newNode;
                newNode.parent = parent;
                return;
            }
        }else{
            current = current.right;
            if(current==null){
                parent.right = newNode;
                newNode.parent = parent;
                return;
            }
        }
    }
}

Without recursion insertion of 1 to n numbers.

public static void main(String arg[]){
    Solution2 s = new Solution2();
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    for(int i = 1;i <= n;i++){
        s.insert(i);
    }

}


来源:https://stackoverflow.com/questions/42615150/how-to-create-a-binary-search-tree-that-includes-all-numbers-from-1-to-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!