劍指 Offer 33. 二叉搜尋樹的後序遍歷序列(遞迴)1
阿新 • • 發佈:2020-12-14
技術標籤:LeetCode
輸入一個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷結果。如果是則返回true,否則返回false。假設輸入的陣列的任意兩個數字都互不相同。
參考以下這顆二叉搜尋樹:
5
/ \
2 6
/ \
1 3
示例 1:
輸入: [1,6,3,2,5]
輸出: false
示例 2:
輸入: [1,3,2,6,5]
輸出: true
解法一:遞迴
class Solution { public boolean verifyPostorder(int[] postorder) { return recur(postorder, 0, postorder.length - 1); } boolean recur(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 && recur(postorder, i, m - 1) && recur(postorder, m, j - 1); } }