Finding last element of a binary heap

后端 未结 6 1275
小鲜肉
小鲜肉 2020-12-09 10:59

quoting Wikipedia:

It is perfectly acceptable to use a traditional binary tree data structure to implement a binary heap. There is an

6条回答
  •  渐次进展
    2020-12-09 11:30

    Solution in case you don't have reference to parent !!! To find the right place for next node you have 3 cases to handle

    • case (1) Tree level is complete Log2(N)
    • case (2) Tree node count is even
    • case (3) Tree node count is odd

    Insert:

    void Insert(Node root,Node n)
    {
    Node parent = findRequiredParentToInsertNewNode (root);
    if(parent.left == null)
    parent.left = n;
    else
    parent.right = n;
    }
    

    Find the parent of the node in order to insert it

    void findRequiredParentToInsertNewNode(Node root){
    
    Node last = findLastNode(root);
    
     //Case 1 
     if(2*Math.Pow(levelNumber) == NodeCount){
         while(root.left != null)
          root=root.left;
      return root;
     }
     //Case 2
     else if(Even(N)){
       Node n =findParentOfLastNode(root ,findParentOfLastNode(root ,last));
     return n.right;
     }
    //Case 3
     else if(Odd(N)){
      Node n =findParentOfLastNode(root ,last);
     return n;
     }
    
    }
    

    To find the last node you need to perform a BFS (breadth first search) and get the last element in the queue

     Node findLastNode(Node root)
     {
         if (root.left == nil)
             return root
    
         Queue q = new Queue();
    
         q.enqueue(root);
         Node n = null;
    
         while(!q.isEmpty()){
          n = q.dequeue();
         if ( n.left != null )
             q.enqueue(n.left);
         if ( n.right != null )
             q.enqueue(n.right);
            }
       return n;
    }
    

    Find the parent of the last node in order to set the node to null in case replacing with the root in removal case

     Node findParentOfLastNode(Node root ,Node lastNode)
    {
        if(root == null)
            return root;
    
        if( root.left == lastNode || root.right == lastNode )
            return root;
    
        Node n1= findParentOfLastNode(root.left,lastNode);
        Node n2= findParentOfLastNode(root.left,lastNode);
    
        return n1 != null ? n1 : n2;
    }
    

提交回复
热议问题