Heap ============ A heap (پشته) is divided into two categories: min heap and max heap. In a min heap (پشته), the value of each node is smaller than its children, and in a max heap (پشته), the value of each node is larger than its children. In a heap, the leaves are located in the last two levels. (Insertion) Insertion --------------------- The steps for adding x to a min heap are as follows (the steps are similar for a max heap): - Place x in the last level by connecting it to a node in the second-to-last level that does not yet have two children. If such a node does not exist, add a new level and connect x to a node in the level above. - Now, compare x with its parent. If x's value is less than its parent's, swap their positions. Continue this step until x becomes the root or its value is greater than its parent's. .. (Deletion) Deletion -------------------- The steps for deletion in a min heap are as follows (the steps are similar for a max heap): - Swap the value of the root with the value of one of the leaves in the last level, then remove that leaf. At this stage, the root's value has changed, so we must check if it satisfies the min heap condition. Let y be the smaller value between the root's children. If the root is greater than y, we swap the root and y, and then repeat this step for the subtree where the root is now located.