二叉搜索树的后序遍历序列
Hard;
Last updated
Hard;
Last updated
[4,8,6,12,16,14,10]true 5
/ \
3 7
/ \ / \
1 2 6 8
pre-order: 5, 3, 1, 2, 7, 6, 8
post-order: 1,2,3,6,8,7,5
inverse post-order: 5, 7, 8, 6, 3, 2,1# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
#idea:
# in post-order BST, the last node in sequence = root node
#1. find the root node at the end of seq and iterate node before root node to find the
# start from right to left, find the first node with val < root val
#
#then partition subarray by this boundary to get left subtree and right subtree
# and pass the root val to the recursion
# For left subtree, find the root of left subtree and find the boundary
# of element < root of left and <parent root, if find any element > parent root
# return False
# similar to left subtree, right subtree do the same thing
#
# post-order traversal 的特点是
# 从右往左iterate array相对于 current-node-> right node->left node的方向的遍历
# 相当于和pre-order的对称
#
#
if not sequence:
return False
max_val = float('inf')
min_val = -float('inf')
stack = [min_val]
for i in range(len(sequence)-1, -1, -1):
if sequence[i] > max_val:
return False
# pop the right subtree values
# and find the node of left subtree
while sequence[i] < stack[-1]:
max_val = stack.pop(-1)
stack.append(sequence[i])
return True