首页 > 其他 > 详细

二叉搜索树的操作

时间:2018-07-31 16:14:56      阅读:145      评论:0      收藏:0      [点我收藏+]

2018-07-31 15:46:34

一、插入 Insert into a Binary Search Tree

问题描述:

技术分享图片

技术分享图片

问题求解:

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

 

二、删除 Delete Node in a BST

问题描述:

技术分享图片

技术分享图片

问题求解:

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;
        if (root.val > key) root.left = deleteNode(root.left, key);
        else if (root.val < key) root.right = deleteNode(root.right, key);
        else {
            if (root.left == null) return root.right;
            if (root.right == null) return root.left;
            TreeNode minNode = root.right;
            while (minNode.left != null) minNode = minNode.left;
            root.val = minNode.val;
            root.right = deleteNode(root.right, root.val);
        }
        return root;
    }

 

二叉搜索树的操作

原文:https://www.cnblogs.com/TIMHY/p/9396317.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!