forked from super30admin/Trees-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IterativeBST.py
44 lines (27 loc) · 894 Bytes
/
IterativeBST.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Trees-1
## Problem 1
#Validate BST using Recursion
# Time Complexity = O(n)
# Space Complexity = O(h)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isValidBST(self, root):
BST = []
prevElement = None
# if BST is not empty and root is not null
while BST or root:
while root:
BST.append(root)
root = root.left
# pop the root element
root = BST.pop()
if(not prevElement and prevElement.val >= root.val):
return False
prevElement = root
root = root.right
return True