Convert Sorted Array to Binary Search Tree (Picturing the Recursion)

人走茶凉 提交于 2019-12-22 15:09:18

问题


I want to convert a sorted integer array into a binary search tree. I believe I understand how to do this. I have posted my pseudo-code below. What I cannot picture is how the recursion actually works.

So if my array is 1, 2, 3, 4, 5... I first make 3 the root of my BST. Then I make 2 the left-child node of 3. Then do I make 1 the left-child node of 2, and come back to 2? I don't get how the recursion steps through the whole process...

Thanks in advance, and apologies if this question is poorly explained. I don't want explicit code, but I would really appreciate if someone could help me go over how the recursion runs through the problem (i.e. what nodes get visited in what order/how the call stack functions)

Pseudo-code:

Step 1. Create a function that takes in the integer array, an integer start, and an integer end. Start = 0, end = integer array size - 1.

Step 2. Create an integer middle which equals (start + end)/2.

Step 3. Test to see if start > end.

Step 4. If so, return null.

Step 5. Else, make the value at the middle index the root of your tree.

Step 6. Set the left node of the root equal to the function with (array, start, middle - 1).

Step 7. Set the right node of the root equal to the function with (array, middle + 1, end).


回答1:


In Java:

public static BST sortedArrayToBST(int[] arr){
    BST bst = new BST();
    sortedArrayToBST(arr, 0, arr.length-1, bst);
    return bst;
}

private static void sortedArrayToBST(int[] arr, int start, int end, BST bst) {

    if( start == end){
        bst.insert(new Node(arr[start]));
        return;
    }
    else if(start > end) {
        return;
    }
    int middle = (start+end)/2;
    bst.insert(new Node(arr[middle]));
    sortedArrayToBST(arr, start, middle - 1, bst);
    sortedArrayToBST(arr, middle+1, end, bst);
}

TEST:

    int[] arr = {1,2,3,4,5,6,7,8,9};
    BST bst = sortedArrayToBST(arr);
    bst.printInOrder();

OUTPUT

1,2,3,4,5,6,7,8,9,




回答2:


Common Lisp version:

(defun sorted-array->tree (array)
  (loop
     :with olength := (length array)
     :with length := (ceiling olength 2)
     :with result := (make-array length)
     :for i :from 0 :below length
     :for j :from 0 :by 2
     :for k :from 1 :by 2 :do
     (setf (aref result i)
           (if (< k olength)
               (list (aref array j) (aref array k))
               (list (aref array j))))
     :finally
     (return (if (= 1 length)
                 (aref result 0)
                 (sorted-array->tree result)))))

(sorted-array->tree #(1 2 3 4 5 6 7 8 9))

;; ((((1 2) (3 4)) ((5 6) (7 8))) (((9))))

Though it would really depend on how you want to treat uneven leafs.




回答3:


public class ArrayToBst {

    private static int[] arr = { 1, 2, 3, 4, 5, 6, 7 };

    public static void main(String[] args) {

        Node talakorootpreservegareko = getBst(arr, 0, 6); 
        inOrder(talakorootpreservegareko);

    }

    public static Node getBst(int[] arr, int start, int stop) {
        if (start > stop) {
            return null;
        } else {
            int mid = (start + stop) / 2;
            Node root = new Node(arr[mid]); 
            System.out.println(root.data);
            root.left = getBst(arr, start, mid - 1);
            root.right = getBst(arr, mid + 1, stop);
            // System.out.print(root.data + " \t");
            return root;
        }
    }

    public static void inOrder(Node parent) {
        if (parent != null) {
            inOrder(parent.left);
            System.out.print(" data " + parent.data + "\t");
            inOrder(parent.right);
        }
    }
}



回答4:


minimalBST(root, arr, 0, len(arr) - 1)
def minimalBST(root, arr, start, end):

    if start > end
        return
        mid = (start + end) // 2 
        root = CreateNode(arr[mid])
        minimalBST(root.left, arr, start, mid - 1)
        minimalBST(root.right, arr, mid + 1, end)

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

arr = [1,2,3,4,5,6,7] since len(arr) = 7 floor(log(7)) = 2 Tree must be formed with at max height 2

      4

    /   \

   2     6  
  / \   / \

 1   3 5   7

minmalBST(root, arr, 0, 6) -> root = 4

minimalBST(root.left, arr, 0, 2) -> root.left = 2

minimalBST(root.left.left, arr, 0, 0) -> root.left.left = 1

minimalBST(root.left.left.left, arr, 0, -1) -> None

minimalBST(root.left.right, arr, 2, 2) -> root.left.right = 2

minimalBST(root.left.right.left, 3, 2) -> None

minimalBST(root.right, arr, 4, 6) -> root.right = 6

minimalBST(root.right.left, arr, 4, 4) -> root.right.left = 5

minimalBST(root.right.left.left, arr, 4, 3) -> None

minimalBST(root.right.right, arr, 6, 6) -> root.left.right = 7

minimalBST(root.right.right.left, 3, 2) -> None



来源:https://stackoverflow.com/questions/19739343/convert-sorted-array-to-binary-search-tree-picturing-the-recursion

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