【问题标题】:Balance Binary tree Coding平衡二叉树编码
【发布时间】:2015-01-08 02:52:27
【问题描述】:

大家好,我刚开始在我的课程中学习二叉树,最近有人问我这个问题。由于我令人难以置信的糟糕实施和对问题的理解不足,我只是不知道如何解决这个问题。请帮帮我!!!

如果对于任何节点 u,则称具有 n 个节点的二叉树 T 是 h-balance 在 T 中,它的两个子树的高度之差最多为 h,其中 h >= 0 是一个整数。假设一棵空树的高度为-1。假设你有每个节点 三个字段:u.lc 指向 u 的左孩子,如果 u 没有左孩子,则 u.lc = NULL 孩子; u.rc 指向 u 的右孩子,如果 u 没有右孩子,则 u.rc = NULL; u.height 应设置为以 u 为根的树的高度。

(a) 给定指向树根的 r,用伪代码设计一个算法 (或 C/C++)在 u:height 中填充每个节点 u 的高度。

(b) 假设每个节点 u 的高度存储在 u.height 中,写一个算法 检查T是否是h平衡的。 (提示:修改(a)中设计的算法)

【问题讨论】:

    标签: c++ c algorithm tree binary-tree


    【解决方案1】:

    这甚至不是伪代码,但应该对您有所帮助。

    如果您更正式地陈述问题的条件,通常会使问题更清楚:

    一)

    • 叶子的高度是-1
    • 内部节点的高度比其两个子树的高度最大值大一。

    b)

    • 叶子是 h 平衡的
    • 当且仅当它的两个子树都是 h 平衡的并且它们的高度之差最多为 h 时,一个内部节点是 h 平衡的。

    如您所见,这两个问题都遵循相同的模式:一个叶子案例,一个依赖于两个子树的案例。

    这是二叉树上递归的一般形式:

    void recurse(t)
    {
        if (t is a leaf, i.e. an empty tree)
        {
           handle the leaf case
        }
        else
        {
            do something that depends on 
               recurse(left subtree of t) 
            and 
               recurse(right subtree of t)
        }
    }
    

    我将剩下的解决方案留作练习。

    【讨论】:

      【解决方案2】:

      这是一个算法。假设节点结构声明如下:

      struct Node {
          Node *l;    // left child
          Node *r;    // right child
          int   h;    // subtree height
      };
      

      然后

      void CalcHeights(Node *n)
      {
          if(n != NULL)
          {
              CalcHeights(n->l);  // calc height in subtrees
              CalcHeights(n->r);
              int hl = n->l ? n->l->h : -1;   // read calculated heights
              int hr = n->r ? n->r->h : -1;
      
              n->h = (hl > hr ? hl : hr) + 1; // get the bigger one plus 1
          }
      }
      
      bool TestBalanced(Node const *n, int h)
      {
          if(n != NULL)
          {
              if(! TestBalanced(n->l, h) || ! TestBalanced(n->r, h))
                  return false;               // unbalanced subtree...
      
              int hl = n->l ? n->l->h : -1;   // get subtrees heights
              int hr = n->r ? n->r->h : -1;
      
              return abs(hl - hr) <= h;   // test the difference against H
          }
          return true;  // empty tree is balanced
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-13
        • 2018-08-30
        • 1970-01-01
        • 1970-01-01
        • 2013-12-18
        相关资源
        最近更新 更多