Creating a Binary Search Tree from a sorted array

前端 未结 3 1993
醉话见心
醉话见心 2020-12-18 07:50

I am currently checking about coding an algorithms. If we have the following case:

Given a sorted (increasing order) array with unique integer elements, wrote an alg

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 08:37

    Reference GeeksForGeeks

    Algorithm -

    1. Get the Middle of the array and make it root.
    2. Recursively do same for left half and right half.
      • Get the middle of left half and make it left child of the root created in step 1.
      • Get the middle of right half and make it right child of the root created in step 1.

    Wikipedia Link

    CODE

     class Node {
    
        int data;
        Node left, right;
    
        Node(int d) {
            data = d;
            left = right = null;
        }
    }
    
    class BinaryTree {
    
        static Node root;
    
        /* A function that constructs Balanced Binary Search Tree 
        from a sorted array */
        Node sortedArrayToBST(int arr[], int start, int end) {
    
            /* Base Case */
            if (start > end) {
                return null;
            }
    
            /* Get the middle element and make it root */
            int mid = (start + end) / 2;
            Node node = new Node(arr[mid]);
    
            /* Recursively construct the left subtree and make it
            left child of root */
            node.left = sortedArrayToBST(arr, start, mid - 1);
    
            /* Recursively construct the right subtree and make it
            right child of root */
            node.right = sortedArrayToBST(arr, mid + 1, end);
    
            return node;
        }
    
        /* A utility function to print preorder traversal of BST */
        void preOrder(Node node) {
            if (node == null) {
                return;
            }
            System.out.print(node.data + " ");
            preOrder(node.left);
            preOrder(node.right);
        }
    
        public static void main(String[] args) {
            BinaryTree tree = new BinaryTree();
            int arr[] = new int[]{2, 4, 6, 8, 10, 12};
            int n = arr.length;
            root = tree.sortedArrayToBST(arr, 0, n - 1);
            System.out.println("Preorder traversal of constructed BST");
            tree.preOrder(root);
        }
    }
    

提交回复
热议问题