二叉搜尋樹的後序遍歷

2021-09-25 07:08:24 字數 1219 閱讀 8859

題目描述:

輸入乙個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷的結果。如果是則輸出yes,否則輸出no。假設輸入的陣列的任意兩個數字都互不相同。

思路:兒叉搜尋樹:(二叉排序樹) 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值; 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值; 它的左、右子樹也分別為二叉排序樹。(左《根,右》根)

即:後序序列最後乙個值為root;二叉搜尋樹左子樹值都比root小,右子樹值都比root大。

1、確定root;

2、遍歷序列(除去root結點),找到第乙個大於root的位置,則該位置左邊為左子樹,右邊為右子樹;

3、遍歷右子樹,若發現有小於root的值,則直接返回false;

4、分別判斷左子樹和右子樹是否仍是二叉搜尋樹(即遞迴步驟1、2、3)。

**說明:用index來區分根節點的左右子樹。

# -*- coding:utf-8 -*-

class solution:

def verifysquenceofbst(self, sequence):

# write code here

length = len(sequence)

if not sequence:

return false

if length<2:

return true

root = sequence[-1]

index = 0

i=0while sequence[i]i=i+1

index = i

for j in range(i, length-1):

if sequence[j] < root:

return false

left = sequence[:index]

right = sequence[index:-1]

result = true

if left:

result = self.verifysquenceofbst(left)

if right:

result = result and self.verifysquenceofbst(right)

return result

二叉搜尋樹的後序遍歷

二叉搜尋樹的後序遍歷序列中,最後乙個值是根結點,前面比根節點小的是左結點,後面比根結點大的是右結點。include include bool verifysquenceofbst int sequence,int length int root sequence length 1 int i 0 在...

二叉搜尋樹的後序遍歷

描述 輸入乙個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷。如果是,則輸出yes,否則輸出no。假設輸入的陣列的任意兩個數字都互不相同。1 樣例輸入 5 7 6 9 11 10 8 1 樣例輸出 yes 2 樣例輸入 7 4 6 5 2 樣例輸出 no 首先要知道二叉搜尋樹的定義 或者是一棵空樹...

二叉搜尋樹的後序遍歷

輸入乙個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷的結果。如果是則輸出yes,否則輸出no。假設輸入的陣列的任意兩個數字都互不相同。思路採用遞迴方法 include include includeusing namespace std bool core vectorsequence,int ...