二叉搜索树的插入、删除、查找。

75 阅读1分钟

二叉搜索树的插入、删除、查找

二叉搜索树的模板

if (root == null) {
   
}
if (root.val == val) {
  
} else if (root.val < val) {
  
} else if (root.val > val) {
  
}
return

700. 二叉搜索树中的搜索

  public TreeNode searchBST(TreeNode root, int val) {
        if (root == null) {
            return null;
        }
        if (root.val < val) {
            return searchBST(root.right, val);
        }
        if (root.val > val) {
            return searchBST(root.left, val);
        }
        return root;
    } 

701. 二叉搜索树中的插入操作

public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);
        if (root.val > val) {
            root.left = insertIntoBST(root.left, val);
        }
        if (root.val < val) {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }

450. 删除二叉搜索树中的节点

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;
        if (root.val == key) {
            if (root.left == null && root.right == null) return null; // 与下面两行代码冗余,可以删去,这里为了分类讨论;
            if (root.left == null) return root.right;
            if (root.right == null) return root.left;
            // 左子树 和 右子树 && != null
​
            TreeNode minNode = root.right;
            while (minNode.left != null) minNode = minNode.left;
            minNode.left = root.left;
            root = root.right;
        } else if (root.val < key) {
            root.right = deleteNode(root.right, key);
        } else if (root.val > key) {
            root.left = deleteNode(root.left, key);
        }
        return root;
    }
​