二叉搜索树的后序遍历序列
二叉搜索树的后序遍历序列
http://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd
看到题目的标题中有标签栈,一直在思考使用栈的解法,奈何能力有限,最终还是没想出来,自己想的解法是递归解法,即确定左右子树后递归判断左右子树:
public class Solution { public boolean VerifySquenceOfBST(int [] a) { if (a == null || a.length == 0) { return false; } return verify(a, 0, a.length - 1); } private boolean verify(int[] a, int s, int e) { if (s >= e) return true; // 上车先系安全带,安全第一 int root = a[e]; int p1 = s; while (a[p1] < root) { ++p1; // 找到右子树的开始下标 } if (p1 == e) { return verify(a, s, e - 1); // 没有右子树的场景 } else { for (int i = p1; i < e; ++i) { if (a[i] < root) { return false; // 右子树中不能有比当前根节点更小的值 } } return verify(a, s, p1 - 1) && verify(a, p1, e - 1); } } }