劍指offer66題--Java實現,c++實現和python實現 23.二叉搜尋樹的後序遍歷序列
阿新 • • 發佈:2018-12-29
題目描述
輸入一個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的陣列的任意兩個數字都互不相同。
C++
class Solution { public: bool VerifySquenceOfBST(vector<int> sequence) { return sequence.size()==0? false:SquenceOfBST(sequence,0,sequence.size()); } bool SquenceOfBST(vector<int> &sequence, int l, int r) { if (l == r) return true; int mid = l, last = 0; for (; mid < r - 1 && sequence[mid] < sequence[r - 1]; ++mid); for (last = mid; last < r - 1 && sequence[last] > sequence[r - 1]; ++last); return last == r - 1 && SquenceOfBST(sequence, l, mid) && SquenceOfBST(sequence, mid, r - 1); } };
Java
public class Solution { public boolean VerifySquenceOfBST(int [] sequence) { if (null == sequence || sequence.length == 0) { System.out.println("陣列為null"); return false; } int n = sequence.length; return verify(sequence, 0, n-1); } private boolean verify(int [] sequence, int start, int stop) {//最開始的start表示索引0,stop表示索引為n-1 if (start >= stop) { return true; } int root = sequence[stop];//拿到根節點 int i = start; for (;i<stop;i++) {//一直到當前的根節點 if (root < sequence[i]) {//當找到大於root節點的元素時跳出來 break; } } int j = i;//之所以換一個變數,是為了儲存 i此時所在的位置,方便之後針對左右子樹分別處理 for (;j<stop;j++) { if (root > sequence[j]) {//如果二叉搜尋樹的右子樹中有比root節點小的節點,則證明不對 return false; } } return verify(sequence, start, i-1) && verify(sequence, i, stop-1); } }
python
class Solution: def VerifySquenceOfBST(self, sequence): if sequence == []: return False if len(sequence) == 1 or len(sequence) == 2: return True else: root = sequence.pop(-1) sign = 0 note = 0 flag = 0 for i in range(len(sequence)): if sign is 0 and sequence[i] > root: note = i sign = -1 if sequence[i] > root: sign = 1 flag += 1 if (sign == 1) and (sequence[i] < root): return False if sign is 0: note = i if flag == len(sequence): note = 1 return self.VerifySquenceOfBST(sequence[:note]) and self.VerifySquenceOfBST(sequence[note:])