Question

in PYTHON   create a binary search tree that has the minimum possible height (i.e., is as balanced...

in PYTHON   create a binary search tree that has the minimum possible height (i.e., is as balanced as possible). You're given the elements in sorted order.

Here are some example inputs and the minimum possible height of the resulting BST:

[0]    0
[-3, -2, -1]    1
[-3, 0, 1, 3, 4]    2
[-9, -6, -5, -3, -2, 1, 2, 4, 8]    3
[-19, -17, -15, -12, -11, -9, -7, -1, 1, 4, 5, 7, 8, 9, 11, 12, 13, 14, 18]    4

class TreeNode:
'''Node for a simple binary tree structure'''
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right


def min_height_BST(alist):
'''Returns a minimum-height BST built from the elements in alist (which are in sorted order)'''

0 0
Add a comment Improve this question Transcribed image text
Answer #1

class TreeNode:
        '''Node for a simple binary tree structure'''
        def __init__(self, value, left=None, right=None):
                self.value = value
                self.left = left
                self.right = right

        def printInOrder(self):
                if self.left:
                        self.left.printInOrder()
                print(self.value)
                if self.right:
                        self.right.printInOrder()

def fillTree(nums):
        if len(nums) == 0:
                return None
        if len(nums) == 1:
                return TreeNode(nums[0])
        mid = len(nums)//2
        left = None
        right = None
        if mid != 0:
                left = fillTree(nums[:mid])
        if mid != len(nums) - 1:
                right = fillTree(nums[mid + 1:])

        return TreeNode(nums[mid], left, right)

nums = [-19, -17, -15, -12, -11, -9, -7, -1, 1, 4, 5, 7, 8, 9, 11, 12, 13, 14, 18]
x = fillTree(nums)
x.printInOrder()


   Please upvote, as i have given the exact answer as asked in question. Still in case of any issues in code, let me know in comments. Thanks!

Add a comment
Know the answer?
Add Answer to:
in PYTHON   create a binary search tree that has the minimum possible height (i.e., is as balanced...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT