美文网首页
701. 二叉搜索树中的插入、搜索、删除操作

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

作者: 编程小王子AAA | 来源:发表于2020-08-15 08:21 被阅读0次

二叉搜索树中的插入、搜索、删除操作


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
//插入
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);

        // insert into the right subtree
        if (val > root.val) root.right = insertIntoBST(root.right, val);
        // insert into the left subtree
        else root.left = insertIntoBST(root.left, val);
        return root; 
    }
}
//搜索
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        while (root != null && val != root.val)
        root = val < root.val ? root.left : root.right;
        return root;
    }
}
//删除操作见第450题

相关文章

网友评论

      本文标题:701. 二叉搜索树中的插入、搜索、删除操作

      本文链接:https://www.haomeiwen.com/subject/yrvpdktx.html