Skip to content

Commit

Permalink
core: add 二叉搜索树的后序遍历序列
Browse files Browse the repository at this point in the history
  • Loading branch information
elonehoo committed Apr 23, 2022
1 parent 08c044c commit 3f5b2f4
Showing 1 changed file with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -314,3 +314,48 @@ export function reversePairs(nums: number[]): number {

return ans;
};

/**
* 剑指 Offer 33. 二叉搜索树的后序遍历序列
*
* 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
* 参考以下这颗二叉搜索树:
* 5
* / \
* 2 6
* / \
* 1 3
*
* 示例 1:
* 输入: [1,6,3,2,5]
* 输出: false
* 示例 2:
* 输入: [1,3,2,6,5]
* 输出: true
*
* 提示:
* 数组长度 <= 1000
*
* @param postorder 整数数组
*
* @return 判断该数组是不是某二叉搜索树的后序遍历结果
*/
export function verifyPostorder(postorder: number[]): boolean {
return recur(postorder, 0, postorder.length - 1)
};

function recur(postorder:number[],i:number,j:number):boolean{
if(i >= j){ return true }
let p:number = 0

while(postorder[p] < postorder[j]){
p++
}

let m:number = 0
while(postorder[p] > postorder[j]){
p++
}
return p == j && recur(postorder, i, m - 1) && recur(postorder, m, j - 1);

}

0 comments on commit 3f5b2f4

Please sign in to comment.