From 09c817652dfbc68299675d41dbb12ef4b387f6e7 Mon Sep 17 00:00:00 2001 From: Ahmed Ossama <58595131+AhmedOssama22dev@users.noreply.github.com> Date: Tue, 6 Oct 2020 03:02:05 +0200 Subject: [PATCH] Create Unsorted arr to balanced bst.py Solving issue of converting unsorted array to a balanced bst --- Trees/Unsorted arr to balanced bst.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Trees/Unsorted arr to balanced bst.py diff --git a/Trees/Unsorted arr to balanced bst.py b/Trees/Unsorted arr to balanced bst.py new file mode 100644 index 0000000..b74ba68 --- /dev/null +++ b/Trees/Unsorted arr to balanced bst.py @@ -0,0 +1,19 @@ +''' +This creates a BALANCED BST from an unsorted array. + +Tree() is a class create instance of a root node. (This is already implemented in other files in the repo) +''' + +def toBst(arr): + arr.sort() + def toBalanced(arr): + if(not arr): + return None + + mid=len(arr)//2 + root=Tree(arr[mid]) + root.left=toBalanced(arr[0:mid]) + root.right=toBalanced(arr[mid+1:]) + + return root + return toBalanced(arr)