题目
- 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则返回true。否则返回false。假设输入的数组的任意两个数字都互不相同。
- leetcode链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/
思路
- 排出中序序列,再判断是否是递增数组
代码
/**
* @param {number[]} postorder
* @return {boolean}
*/
var verifyPostorder = function (postorder) {
if (!postorder.length) return true
function order(arr) {
if (!arr.length) return []
if (arr.length === 1) return arr
const root = arr.pop()
let i = 0
while (i < arr.length && arr[i] < root) i++
const left = arr.slice(0, i)
const right = arr.slice(i)
return [...order(left), root, ...order(right)]
}
const zhongxu = order(postorder)
for (let i = 1; i < zhongxu.length; i++) {
if (zhongxu[i] < zhongxu[i-1]) return false
}
return true
}