簡體   English   中英

未排序的數組到二進制搜索樹

[英]unsorted Array to Binary Search Tree

因此,我確信這非常簡單,我只是想念它,但我需要對BST做一個未排序的數組。 我有一個數組int [] data = {50,30,60,10,80,55,40}; 而且無論我將其更改為什么,我都需要將第一個數字轉換為不平衡的BST,而其他數字則遵循左右規則。 我有適用於此數組的代碼,但如果我將數字更改為不在中間的內容,則不會。

 public Node arraytoBinary(int [] array, int start, int end) {
    if (start > end){
        return null;
    }
    int mid = (start + end) / 2;
    Node node = new Node(array[mid]);
   node.left = arraytoBinary(array, start, mid - 1);
   node.right = arraytoBinary(array, mid + 1, end);

    return node;
}    

我真的不明白為什么您嘗試拆分數組,並且您似乎對值及其順序進行了一些假設。 (盡管說實話,我還沒有運行您的代碼)您不能僅僅認為要走的方向(左,右)。 它取決於當前元素的值和當前節點保存的值。

我的方法是定義一個insert(Node node, int value)方法,並讓arrayToBinary簡單地迭代數組並調用insert 這將為您提供帶有最少接口的干凈樹。 另外,它基於BST的定義和插入邏輯,因此應該直觀。

(為您的快樂而假)
插入


Node insert(node, value)
    if node is null
        // Create a leaf.
        // It might be the root...
        return new Node(value)

    // It's occupied, see which way to
    // go based on it's value

    // right? ...
    if value > node.value
        node.right = insert(node.right, value)

    // or left?
    else if value < node.value
        node.left = insert(node.left, value)

    // Code is not handling dups.
    return node

轉換次數


Node arrayToBinary(array, root)
    for e in array
        root = insert(root, e)
    return root

這會將第一個元素保留為根,並按預期插入數組的其余部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM