【问题标题】:Algorithm for checking if an Array with n-elements is a minimum heap检查具有 n 个元素的数组是否是最小堆的算法
【发布时间】:2011-05-08 14:45:19
【问题描述】:

我正在尝试概述一种算法来确定我的数组是否是最小堆。是否有任何文件可以帮助我解决这个问题?我在 Apache 的网站上找到了它的一个函数,但它并没有准确地显示该函数是如何工作的;只是存在一个函数(BinaryHeap(boolean isMinHeap))。

【问题讨论】:

    标签: arrays tree heap minimum


    【解决方案1】:

    The Wikipedia article 应该可以帮到你。

    这里有一些问题可以帮助您思考解决方案:

    1. 假设堆是最小堆,那么堆的根必须是什么?
    2. 如果堆的根满足最小堆属性,如何确保根的子树也持有该属性?
    3. 如果树的根没有孩子怎么办?是最小堆吗?

    【讨论】:

      【解决方案2】:

      我认为这会奏效!

      bool checkminheap(int arr[],root)
      {
           if(root>=sizeof(arr)/sizeof(arr[0])-1)
               return 1;
           if(arr[root]>arr[2*root] || arr[root]>arr[2*root+1])  //check root is the smallest element
            return 0; 
          if(!checkminheap(arr,2*root))//check leftsubtree
            return 0;
          if(!checkminheap(arr,2*root+1))//check rightsubtree
            return 0;
      
           return 1;
      }  
      

      【讨论】:

        【解决方案3】:

        添加一个带有java泛型支持的详细解决方案,它相对更容易遵循。

        public static <T extends Comparable<T>> boolean isMinHeap(T arr[], int rootIndex) {
          boolean isMaxH = true;
          int lChild = 2 * rootIndex + 1;
          int rChild = 2 * rootIndex + 2;
        
          // Nothing to compare here, as lChild itself is larger then arr length.
          if (lChild >= arr.length) {
            return true;
          }
        
          if (arr[rootIndex].compareTo(arr[lChild]) > 0) {
            return false;
          } else {
            isMaxH = isMaxH && isMinHeap(arr, lChild);
          }
        
          // rChild comparison not needed, return the current state of this root.
          if (rChild >= arr.length) {
            return isMaxH;
          }
        
          if (arr[rootIndex].compareTo(arr[rChild]) > 0) {
            return false;
          } else {
            isMaxH = isMaxH && isMinHeap(arr, rChild);
          }
        
          return isMaxH;
        }
        

        【讨论】:

          猜你喜欢
          • 2021-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-01
          • 2021-10-10
          • 2019-02-24
          • 1970-01-01
          • 2017-11-26
          相关资源
          最近更新 更多