“`” 参考回答:

BST(二叉排序树):

1、每个结点都有一个作为搜索依据的关键码,所有结点的关键码不同

2、左子树上所有结点的关键码小于根节点的关键码

3、右子树所有结点的关键码大于根节点的关键码

4、左子树和右子树也是BST

判断一棵树是不是BST

<pre><code class=""language-c"" lang=""c"">class Node {
int data;
Node left;
Node right;
}
public class BSTChecker {
private static int lastVisit = Integer.MIN_VALUE;
public static boolean isBST(Node root) {
if(root == null) return true;
boolean judgeLeft = isBST(root.left); // 先判断左子树
if(root.data >= lastVisit && judgeLeft) { // 当前节点比上次访问的数值要大
lastVisit = root.data;
} else {
return false;
}
boolean judgeRight = isBST(root.right); // 后判断右子树
return judgeRight;
}
}

</code></pre>

 

 

<pre><code> "“`

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.