SoFunction
Updated on 2025-03-01

Example of deletion algorithm of binary tree of JavaScript data structure

This article describes the deletion algorithm of the binary tree of JavaScript data structure. Share it for your reference, as follows:

The complexity of deleting nodes from a binary search tree depends on which node is deleted. It is very simple to delete a node without child nodes. If the node has only one child node, whether it is the left child node or the right child node, it becomes a little complicated. If the node contains two child nodes, it is the most complicated.

If the node to be deleted is a leaf node, then you only need to point the link pointed from the parent node to it to null

If the node to be deleted contains only one child node, then the node that originally pointed to it must point to its child node

If the node to be deleted contains two child nodes, then we can adopt two methods. One is to find the maximum value on the left subtree of the node to be deleted, and the other is to find the minimum value on the right node of the node to be deleted.. We take the latter, after finding the minimum value, copy the value on the temporary node to the node to be deleted, and then delete the temporary node.

The code for the deletion operation is as follows:

function getSmallest(node){//Find the smallest node    while(!=null){
      node=;
    }
    return node;
}
function remove(data){
    root=removeNode(,data);//Convert the root node}
function removeNode(node,data){
    if(node==null){
      return null;
    }
    if(data==){
      //If there are no children      if(==null&&==null){
        return null;//Set the node directly to empty      }
      //If there is no left child node      if(==null){
        return ;//Point directly to its right node      }
      //If there is no right child node      if(==null){
        return ;
      }
      //If there are two nodes      if(!=null&&!=null){
        var tempNode=getSmallest();//Find the smallest right node        =;
        =removeNode(,);//Search in turn        return node;
      }
    }else if(data<){
      =removeNode(,data);
      return node;
    }else{
      =removeNode(,data);
      return node;
    }
}

For more information about JavaScript, readers who are interested in reading this site's special topic:Summary of JavaScript data structure and algorithm techniques》、《Summary of JavaScript mathematical operations usage》、《Summary of JavaScript sorting algorithm》、《JavaScript traversal algorithm and skills summary》、《Summary of JavaScript search algorithm skills"and"Summary of JavaScript Errors and Debugging Skills

I hope this article will be helpful to everyone's JavaScript programming.