Iam_Sandeep

1008. Construct Binary Search Tree from Preorder Traversal

Apr 20th, 2022
1,110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.41 KB | None | 0 0
  1. class Solution:
  2.     def bstFromPreorder(self, pre: List[int]) -> Optional[TreeNode]:
  3.         i=0
  4.         n=len(pre)
  5.         def dfs(right):
  6.             nonlocal i
  7.             if i==n or pre[i]>right:return None
  8.             root=TreeNode(pre[i])
  9.             i+=1
  10.             root.left=dfs(root.val)
  11.             root.right=dfs(right)
  12.             return root
  13.         return dfs(float('inf'))
  14.            
  15.  
Advertisement
Add Comment
Please, Sign In to add comment