判断二叉排序树Java
时间: 2024-11-11 15:04:22 浏览: 22
判断一个给定的二叉树是否是二叉排序树 (BST) 的Java方法通常是通过递归遍历来进行的。BST的特点是对于任意节点,其左子树中的所有节点值都小于该节点值,而右子树的所有节点值都大于该节点值。
以下是判断一个二叉树是否为BST的Java代码示例:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
// 构造函数省略
}
public class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private boolean helper(TreeNode node, int min, int max) {
if (node == null) {
return true;
}
if (node.val <= min || node.val >= max) {
return false;
}
if (!helper(node.left, min, node.val)) {
return false;
}
if (!helper(node.right, node.val, max)) {
return false;
}
return true;
}
}
```
在这个例子中,`isValidBST`方法是主入口,它调用私有辅助方法`helper`。`helper`方法会检查当前节点的值是否在指定范围内(min和max),以及左右子树是否也满足BST条件。如果在整个树中都能保持这个规则,则返回true,否则返回false。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)