GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Algorithm/java/coding/arrayToBinaryTree.java at master · lelea2/Algorithm Expand file tree/ Copy patharrayToBinaryTree.javaMore file actions 68 lines (53 loc) · 1.71 KB / Copy patharrayToBinaryTree.javaFile metadata and controls68 lines (53 loc) · 1.71 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 // Java program to print BST in given range // A binary tree node //Runtime: O(n) // T(n) = 2T(n/2) + C // T(n) --> Time taken for an array of size n // C --> Constant (Finding middle of array and linking root to left // and right subtrees take constant time) 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[]{1, 2, 3, 4, 5, 6, 7}; int n = arr.length; root = tree.sortedArrayToBST(arr, 0, n - 1); System.out.println("Preorder traversal of constructed BST"); tree.preOrder(root); } } |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |