删除二叉查找树的节点

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">1.删除节点函数需要有节点的父节点和结点两个属性,并且分两种情况:</span>

①当删除节点的右节点为空时,删除节点时直接将删除节点的左节点替换删除节点

②当删除节点的右节点不空时,找到删除节点的右节点的最小(最左节点)替换被删除节点,并删除最左节点

 
 
<span style="font-family: Arial, Helvetica, sans-serif;">public TreeNode removeNode(TreeNode root, int value) {</span>

        TreeNode dummy = new TreeNode(0);
        dummy.left = root;
        
        TreeNode parent = findNode(dummy, root, value);
        TreeNode node;
        if (parent.left != null && parent.left.val == value) {
            node = parent.left;
        } else if (parent.right != null && parent.right.val == value) {
            node = parent.right;
        } else {
            return dummy.left;
        }
        
        deleteNode(parent, node);
        
        return dummy.left;
    }
    
    private TreeNode findNode(TreeNode parent, TreeNode node, int value) {
        if (node == null) {
            return parent;
        }
        
        if (node.val == value) {
            return parent;
        }
        if (value < node.val) {
            return findNode(node, node.left, value);
        } else {
            return findNode(node, node.right, value);
        }
    }
    
    private void deleteNode(TreeNode parent, TreeNode node) {
        if (node.right == null) {
            if (parent.left == node) {
                parent.left = node.left;
            } else {
                parent.right = node.left;
            }
        } else {
            TreeNode temp = node.right;
            TreeNode father = node;
            
            while (temp.left != null) {
                father = temp;
                temp = temp.left;
            }
            
            if (father.left == temp) {
                father.left = temp.right;
            } else {
                father.right = temp.right;
            }
            
            if (parent.left == node) {
                parent.left = temp;
            } else {
                parent.right = temp;
            }
            
            temp.left = node.left;
            temp.right = node.right;
        }
    }

 
 



你可能感兴趣的:(二分查找树的删除)