Hi all,
I was doing challenge: 1008 Construct Binary Search Tree from Preorder Traversal and using my following, dumb, approach i get stuck with the input [1,2,3] , according to leetcode my output is [1,null,2,null,null,null,3] and the correct one is [1,null,2,null,3] yet when im debugging it I can't see where those two extra values are coming from.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import copy
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
empty_tree = copy.copy(preorder)
new_tree = [TreeNode(preorder[0])]
preorder.pop(0)
current = 0
while len(preorder) != 0:
new_tree = self.subTree(preorder, new_tree[current], new_tree)
current += 1
for i in range(0, len(new_tree)):
if new_tree[i].val == -1:
new_tree[i].val = 'null'
return new_tree[0]
def subTree(self, preorder, x, new_tree):
left = False
right = False
leftVal = TreeNode(-1)
rightVal = TreeNode(-1)
x_val = x.val
if x_val != -1:
for y in preorder:
if left == False and x_val > y:
#left
left = True
leftVal = TreeNode(y)
if right == False and y >= x_val:
#right
right = True
rightVal = TreeNode(y)
new_tree.append(leftVal)
new_tree.append(rightVal)
x.left = leftVal
x.right = rightVal
if left:
preorder.pop(preorder.index(leftVal.val))
if right:
preorder.pop(preorder.index(rightVal.val))
return new_tree