一、题目
二叉树定义:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
力扣原题:https://leetcode-cn.com/problems/validate-binary-search-tree/
二、递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, null, null);
}
private boolean helper(TreeNode root, Integer low, Integer high) {
if (null == root) {
return true;
}
// 需考虑全局的二叉搜索树,为每个节点设置上下界
if (null != low && root.val <= low) {
return false;
}
// 需考虑全局的二叉搜索树,为每个节点设置上下界
if (null != high && root.val >= high) {
return false;
}
// 递归左子树
if (!helper(root.left, low, root.val)) {
return false;
}
// 递归右子树
if (!helper(root.right, root.val, high)) {
return false;
}
return true;
}
}
- 时间复杂度:最优/最差/平均时间复杂度均为O(n)。每个树节点均需要遍历一次,并判断是否匹配二叉搜索树的定义;
- 空间复杂度:体现在递归的栈空间上,即二叉搜索树的深度。
- 最优:O(log(n+1))。最好的情况下,除了最底层,其他层节点的左右子树均不为空,此时二叉搜索树具有最小深度;
- 最坏:O(n)。最坏的情况下,二叉搜索树可退化为链表;
- 平均:O(log(n))。有兴趣可以推算下;
三、中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if (null == root) {
return true;
}
// 执行中序遍历
List<Integer> list = new ArrayList<>();
inorder(root, list);
// 判断是否为递增数组
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i) >= list.get(i + 1)) {
return false;
}
}
return true;
}
private void inorder(TreeNode node, List<Integer> list) {
// 递归左子树
if (null != node.left) {
inorder(node.left, list);
}
// 添加到列表中
list.add(node.val);
// 递归右子树
if (null != node.right) {
inorder(node.right, list);
}
}
}
- 时间复杂度:最优/最差/平均时间复杂度均为O(n)。中序遍历时间复杂度稳定为O(n),数组遍历的平均时间复杂度为O(n)。
- 空间复杂度:最优/最差/平均时间复杂度均为O(n)。递归的空间复杂度为二叉搜索树的深度,即O(log(n)),通过列表缓存中序遍历的结果,空间复杂度为O(n)。
四、小结
- 二叉搜索树的定义,二叉搜索树既满足链表快速插入/删除的优势,又具有数组快速查找的特性,因而得到广泛应用;
- 二叉搜索树查询的时间复杂度为树的深度,即O(log(n))。极端情况下(插入顺序有序),可退化为链表,此时查询性能退化为O(n);
- 二叉树问题经常可以转化为遍历问题或递归问题;