大家好,都吃晚饭了吗?我是Kaiqisan,是一个已经走出社恐的一般生徒,今天还是二叉树诶嘿嘿
首先还是明确一个概念 ---- 何为序列二叉树
答:中序遍历之后序列递增的二叉树为序列二叉树
比如这棵树
4
/ \
2 7
/ \ / \
1 3 5 8
\
6
它的中序遍历结果为 12345678 为单调递增,所以这棵树为序列二叉树
思路1
所以我们判断的核心思路就是使用当前遍历元素和上一个遍历元素进行比较,所以需要保留当前已经遍历的元素来留作下次判断的筹码
// 临时参数,写在外层,以便在函数全局都可以使用
static int temp = Integer.MIN_VALUE;
static boolean isBST2(Tree head) {
if (head == null) {
return true;
}
boolean left = isBST2(head.left);
if (!left) {
return false;
}
if (head.val <= temp) {
return false;
}
temp = head.val;
boolean right = isBST2(head.right);
if (!right) {
return false;
}
return true;
}
思路2
不使用递归,核心机制就是非递归的中序遍历,顺便保留上一次遍历的节点值(思路1的核心机制)
static boolean isBST(Tree head) {
if (head != null) {
// 临时参数,保留上一次遍历的结果
int temp = Integer.MIN_VALUE;
Stack<Tree> stack = new Stack<>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
if (temp >= head.val) {
return false;
}
temp = head.val;
head = head.right;
}
}
}
return true;
}
总结
没有总结,活用二叉树的遍历就可以了!