題目描述
輸入一個整數數組,判斷該數組是不是某二叉搜索樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的數組的任意兩個數字都互不相同。
思路:
首先要弄清楚二叉搜索樹和二叉樹的後序遍歷。
後序遍歷的序列中,最後一個數字是樹的根節點 ,數組中前面的數字可以分爲兩部分:第一部分是左子樹節點 的值,都比根節點的值小;第二部分 是右子樹 節點的值,都比 根 節點 的值大,後面用遞歸分別判斷前後兩部分 是否 符合以上原則
python
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if sequence==None or len(sequence)==0:
return False
length=len(sequence)
root=sequence[length-1]
# 在二叉搜索 樹中 左子樹節點小於根節點
for i in range(length):
if sequence[i]>root:
break
# 二叉搜索樹中右子樹的節點都大於根節點
for j in range(i,length):
if sequence[j]<root:
return False
# 判斷左子樹是否爲二叉樹
left=True
if i>0:
left=self.VerifySquenceOfBST(sequence[0:i])
# 判斷 右子樹是否爲二叉樹
right=True
if i<length-1:
right=self.VerifySquenceOfBST(sequence[i:-1])
return left and right
c++
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
return bst(sequence,0,sequence.size()-1);
}
bool bst(vector<int> sequence,int begin,int end){
if(sequence.empty()||begin>end)
return false;
int root=sequence[end];
int i=begin;
for(;i<end;++i)
if(sequence[i]>root)//i座標爲右子樹第一個節點
break;
for(int j=i;j<end;++j)
if(sequence[j]<root)
return false;
bool left=true;
if(i>begin)
left=bst(sequence,begin,i-1);
bool right=true;
if(i<end-1)
right=bst(sequence,i,end-1);
return left&&right;
}
};
還是那句話,語言只是實現的方式,重要的是思路!!!