題目描述
輸入一個整數數組,判斷該數組是不是某二叉搜索樹的後序遍歷結果。如果是則返回 true,否則返回 false。假設輸入的數組的任意兩個數字都互不相同。
參考以下這顆二叉搜索樹:
5
/ \
2 6
/ \
1 3
示例 1:
輸入: [1,6,3,2,5]
輸出: false
示例 2:
輸入: [1,3,2,6,5]
輸出: true
思路代碼
- 後續遍歷:左子樹 | 右子樹 | 根
- 左子樹結點的值均小於根節點
- 右子樹結點的值均大於根節點
- 每個孩子結點均滿足以上三點,因此可以遞歸分治
代碼實現:
public class Offer33_VerifyPostorder {
public boolean verifyPostorder(int[] postorder) {
return isPostorder(postorder, 0, postorder.length - 1);
}
private boolean isPostorder(int[] postorder, int i, int j) {
if (i >= j) return true;
int p = i;
while (postorder[p] < postorder[j]) p++;
int m = p;
while (postorder[p] > postorder[j]) p++;
return p == j && isPostorder(postorder, i, m - 1) && isPostorder(postorder, m, j - 1);
}
}