Created
June 5, 2020 11:23
-
-
Save Desolve/751f9e2e2f88ba60f6d45a2708341330 to your computer and use it in GitHub Desktop.
1008 Construct Binary Search Tree from Preorder Traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Definition for a binary tree node. | |
# class TreeNode: | |
# def __init__(self, x): | |
# self.val = x | |
# self.left = None | |
# self.right = None | |
class Solution: | |
i = 0 | |
def bstFromPreorder(self, A, bound=float('inf')): | |
if self.i == len(A) or A[self.i] > bound: | |
return None | |
root = TreeNode(A[self.i]) | |
self.i += 1 | |
root.left = self.bstFromPreorder(A, root.val) | |
root.right = self.bstFromPreorder(A, bound) | |
return root |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment