题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false
关键字: 1.二元查找树 : 二元查找树的特点 第一:左边节点小于右边节点 第一推论:因为中序遍历是先遍历左边再遍历右边,意味着中序遍历是有序的、
2.后序遍历:后续遍历的特点是:先左节点,再右节点,再根节点,所以可以知道后序遍历的最后一个元素是根元素。
我们用分治思想来做:
(a[0]...a[i]) < a[n] < (a[i+1]...a[n-1])
...
a[0]<a[3]<a[1]
public static boolean verifyOfBST(int data[], int begin, int end) {
if (data == null || begin > end)
return false;
if (begin == end) {
return true;
}
int root = data[end];
for (int i = begin; i < end; ++i) {//寻找i,保证左边都小于a[n]
if (data[i] > root)
break;
}
// the nodes in the right sub-tree are greater than the root
for (int j = i; j < end; ++j) { //验证右边都大于a[n]
if (data[j] < root)
return false;
}
// verify whether the left sub-tree is a BST
boolean left = true;
if (i > 0)
left = verifyOfBST(data, begin, i - 1);
// verify whether the right sub-tree is a BST
boolean right = true;
if (i < end)
right = verifyOfBST(data, i, end - 1);
return (left && right);
}
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false
关键字: 1.二元查找树 : 二元查找树的特点 第一:左边节点小于右边节点 第一推论:因为中序遍历是先遍历左边再遍历右边,意味着中序遍历是有序的、
2.后序遍历:后续遍历的特点是:先左节点,再右节点,再根节点,所以可以知道后序遍历的最后一个元素是根元素。
我们用分治思想来做:
(a[0]...a[i]) < a[n] < (a[i+1]...a[n-1])
...
a[0]<a[3]<a[1]
public static boolean verifyOfBST(int data[], int begin, int end) {
if (data == null || begin > end)
return false;
if (begin == end) {
return true;
}
int root = data[end];
for (int i = begin; i < end; ++i) {//寻找i,保证左边都小于a[n]
if (data[i] > root)
break;
}
// the nodes in the right sub-tree are greater than the root
for (int j = i; j < end; ++j) { //验证右边都大于a[n]
if (data[j] < root)
return false;
}
// verify whether the left sub-tree is a BST
boolean left = true;
if (i > 0)
left = verifyOfBST(data, begin, i - 1);
// verify whether the right sub-tree is a BST
boolean right = true;
if (i < end)
right = verifyOfBST(data, i, end - 1);
return (left && right);
}