面试题33

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。

参考以下这颗二叉搜索树:

     5
    / \
   2   6
  / \
 1   3

示例 1:

输入: [1,6,3,2,5]
输出: false

示例 2:

输入: [1,3,2,6,5]
输出: true

提示:

  • 数组长度 <= 1000

Solutions

  1. mono stack

  2. This solution is based on the fact that postorder traversal is the opposite of preorder traversal. ie: preorder(Similar): root right left -> postorder: left right root

  3. Maintain a monotonically increasing stack which records the path when traversing the right subtree(Mono increasing).

  4. This solution works only if there are no duplicate elements in the given sequence.

  1. recursion

  2. In each recursive call, find the first element of the right subtree(val > root->val).

Last updated