Problem statement:
Sort integer array nums
in O(N log N) time,
without relying on any library sort routine.
I am trying to use a tree sort method (using the creation of a BST and then performing inorder traversal) in order to sort an array of numbers. I have the following code:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
output = []
def insert(node, val):
if not node:
return TreeNode(val)
if val <= node.val:
node.left = insert(node.left, val)
else:
node.right = insert(node.right, val)
return node
root = TreeNode(nums[0])
for i in range(1, len(nums)):
root = insert(root, nums[i])
def inorder(root):
if not root:
return
inorder(root.left)
output.append(root.val)
inorder(root.right)
inorder(root)
return output
I am getting a TLE (time limit exceeded) error. I am not sure if there is an optimization to do in order to tighten up time from recursive stack calls in both the insert()
function. I am not sure if the recursive solution is not optimal (given the amount of recursive calls used). Perhaps I need to approach with an iterative approach in order to build the BST during the insert()
calls?