import java.util.Stack;
public class DiDi {
static TreeNode pre = null;
public static boolean isBinarySearchTree(TreeNode root) {//递归实现
if (root == null) {
return true;
}
if (!isBinarySearchTree(root.left)) {//如果左子树不平衡返回false
return false;
}
if (pre != null && pre.val >= root.val) {
return false;
}
pre = root;
return isBinarySearchTree(root.right);//左子树平衡后 比较右子树。
}
public static boolean isBinarySearchTree_notRecursion(TreeNode root) {//非递归实现
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
if (pre != null && pre.val >= root.val) {
return false;
}
pre = root;
root = root.right;
}
}
return true;
}
private class TreeNode {
private TreeNode left;
private TreeNode right;
private Integer val;
public TreeNode(Integer val) {
this.val = val;
}
}
}
判断一个树是否是搜索二叉树
最新推荐文章于 2024-05-17 12:03:01 发布