面試題:二叉搜索樹的後序遍歷
阿新 • • 發佈:2018-08-25
bst public int false nbsp als i++ pub 一個
題目描述:輸入一個整數數組,判斷該數組是不是某二叉搜索樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的數組的任意兩個數字都互不相同。
例子: 8
6 10
5 7 9 11
例如輸入數組{5, 7, 6, 9, 11, 10, 8},則返回true,因為這個整數序列是上圖二叉搜索樹的後序遍歷結果。如果輸入的數組是{7, 4, 6, 5},由於沒有哪顆二叉搜索樹的後序遍歷的結果是這個序列,因此返回false。
代碼:
public classSolution { public boolean VerifySquenceOfBST(int [] sequence) { if(sequence.length==0) return false; return isTreeBST(sequence,0,sequence.length-1); } public boolean isTreeBST(int[]sequence,int start,int end){ if(start>=end) return true; int i=start;while(sequence[i]<sequence[end]&&i<end) i++; for( ;i<end;i++){ if(sequence[i]<sequence[end]) return false; } return isTreeBST(sequence,start,i-1)&&isTreeBST(sequence,i,end); } }
面試題:二叉搜索樹的後序遍歷