【问题标题】:"Capping" a Binary Search Tree (removing all elements > cap)“封顶”二叉搜索树(删除所有元素 > 封顶)
【发布时间】:2017-02-05 21:19:35
【问题描述】:

我想不出一个递归算法来做到这一点。我的尝试是:

void capValue(Node node) {

    if (node == null)
        return

    if (node.element > cap)
        capValue(node.left)
        node = null;
    else // node.element < cap
        capValue(node.right)
}

但是,您不能只清空节点(至少在 java 中,我想在其中编写代码),因为这只会将当前指针移动到地址 0,而我们想要摆脱的对象仍然有一个通过树根指向它的“指针路径”,因此不会被垃圾收集。

【问题讨论】:

    标签: java algorithm binary-tree binary-search-tree graph-theory


    【解决方案1】:

    您可以从函数中返回节点。它可以是这样的:

    Node cap(Node node, int val)
        // There's no node. There's nothing to cap.
        if (node == null)
            return null;
        // The node and it's left subtree should stay
        if node.key <= val {
            node.right = cap(node.right, val);
            return node;
        }
        // The node and it's right subtree must be deleted,
        // so we can go to the left subtree
        return cap(node.left, val);
    

    在后面的代码中应该像 root = cap(root, val) 这样调用它。

    【讨论】:

      【解决方案2】:

      这应该可行。我们将首先找到更大的节点,然后将父链接更新为空。 如果根节点本身大于上限,则为空。

      boolean capValue(Node node) 
      {
      if (node == null)
          return false;
      
      if (node.element > cap) {
      node = null;
      return true;            
      }
      else {// node.element < cap 
           if(capValue(node.right))
           node.right=null;
           return false;  
      }    
      }
      

      【讨论】:

      • 根值为1,左孩子为0cap0
      • 在这种情况下,第一个比较将由第二个 if 块完成,并且 root 将被设置为 null。
      • the root will be set to null - 即使 if 是这样:调用者如何访问 capped 树 (0/left )?
      猜你喜欢
      • 1970-01-01
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      相关资源
      最近更新 更多