二叉搜索树-合法性、增、删、查

1. 定义

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。

拓展:二分搜索

2. 框架

1 void BST(TreeNode root, int target) {
2     if (root.val == target)
3         // 找到目标,做点什么
4     if (root.val < target) 
5         BST(root.right, target);
6     if (root.val > target)
7         BST(root.left, target);
8 }

3. 判断合法性

 1 public boolean isValidBST(TreeNode root) {
 2         return isValidBST(root, null, null);
 3     }
 4     public boolean isValidBST(TreeNode root, TreeNode min, TreeNode max){
 5         if(root == null)
 6             return true;
 7         if(min != null && root.val <= min.val) return false;
 8         if(max != null && root.val >= max.val) return false;
 9         return isValidBST(root.left, min, root) && isValidBST(root.right, root, max);
10     }

4. 查找一个数字

1 boolean isInBST(TreeNode root, int target) {
2     if (root == null) return false;
3     if (root.val == target)
4         return true;
5     if (root.val < target) 
6         return isInBST(root.right, target);
7     if (root.val > target)
8         return isInBST(root.left, target);
9 }

  查找一个数,返回节点及子树

 1 public TreeNode searchBST(TreeNode root, int val) {
 2         if(root == null)
 3             return root;
 4         if(root.val == val)
 5             return root;
 6         if(root.val < val)
 7             return searchBST(root.right, val);
 8         if(root.val > val)
 9             return searchBST(root.left, val);
10         return root;
11     }

5. 插入一个数

1 public TreeNode insertIntoBST(TreeNode root, int val) {
2         if(root == null)
3             return new TreeNode(val);
4         if(root.val < val)
5             root.right = insertIntoBST(root.right, val);
6         if(root.val > val)
7             root.left = insertIntoBST(root.left, val);
8         return root;
9     }

6. 删除一个数

  注意:该节点的左右子树是否有内容?都为空;一个为空;都不为空。

 1 public TreeNode deleteNode(TreeNode root, int key) {
 2         if(root == null)
 3             return null;
 4         if(root.val == key){
 5             if(root.left == null && root.right == null) return null;
 6             if(root.left == null) return root.right;
 7             if(root.right == null) return root.left;
 8             if(root.left != null && root.right != null){
 9                 TreeNode min = getMin(root.right);
10                 root.val = min.val;
11                 root.right = deleteNode(root.right, min.val);
12             }
13         }else if(root.val < key){
14             root.right = deleteNode(root.right, key);
15         }else{
16             root.left = deleteNode(root.left, key);
17         }
18         return root;
19     }
20     public TreeNode getMin(TreeNode node){
21         while(node.left != null)
22             node = node.left;
23         return node;
24 }

猜你喜欢

转载自www.cnblogs.com/Z-D-/p/12629573.html