python3,时间复杂度O(n)的非递归方法。
BST的后序遍历是左右中,逆序后序遍历,就变成了中右左。BST的性质,右一定是大于中的,左一定是小于中的。
设置一个比较参数root,初始化是无穷大。
根部先入栈,如果元素比栈顶大,则是右结点(root是不允许出现左结点后再出现右结点,如果一直是右结点,自然不改变),直接入栈;如果元素比栈顶小,必是左结点,此时找出是谁的左结点,以此更新为root(因为根右左嘛,一旦该结点出现了左结点,就一定不会再出现右结点了)。
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
#先判断数组是否为空
if not sequence:
return False
#初始化根节点为正无穷大
root = float('+inf')
#辅助栈
stack = []
for i in range(len(sequence) -1, -1, -1): #倒序遍历
if sequence[i] > root: #不满足BST
return False
else:
while stack and stack[-1] > sequence[i]: #此时出现左结点,更新root
root = stack.pop()
stack.append(sequence[i]) #一直是右节点入栈
return True

京公网安备 11010502036488号