【问题标题】:Pseudocode for Binary search tree二叉搜索树的伪代码
【发布时间】:2015-04-23 23:18:20
【问题描述】:

在二叉搜索树中,键 x 的前身是键 y,它小于 x,并且没有其他键 z 使得 z 小于 x 或更大 比 y。

给出一个算法的伪代码,它接受一个键 x 并返回 如果 x 是树中最小的键,则前任 y 或 nil。假设二进制 搜索树使用数组 left、right 和 parent 表示。给出伪代码 对于使用的任何辅助功能。

我不太确定如何解决这个问题。但这是我的尝试:

伪代码:

//Takes in key x

BST(x)
{

if ( x < parent[x] )

    return nil

if( parent[x] < x )

   return parent[x] // parent[x] = y
}

【问题讨论】:

    标签: algorithm data-structures binary-search-tree


    【解决方案1】:

    我之前的答案来自对您问题的糟糕阅读 - 您正在寻找的只是树中的前任。 http://www.quora.com/How-can-you-find-successors-and-predecessors-in-a-binary-search-tree-in-order

    这是他们在那篇文章中使用的代码:

    public static TreeNode findPredecessor(TreeNode node)
    {
        if (node == null)
            return null;
    
        if (node.getLeft() != null)
            return findMaximum(node.getLeft());
    
        TreeNode parent = node.getParent();
    
        TreeNode y = parent;
        TreeNode x = node;
        while (y != null && x == y.getLeft())
        {
            x = y;
            y = y.getParent();
        }
    
        return y;
    }
    

    【讨论】:

      【解决方案2】:

      如果不存在任何左节点,则不能有任何前任。否则左子树中的最大元素将是前驱

      public int findmax(Node root) {
           if (root == NULL) 
            return INT_MIN; 
      
          int res = root->data; 
          int lres = findMax(root->left); 
          int rres = findMax(root->right); 
          if (lres > res) 
            res = lres; 
          if (rres > res) 
            res = rres; 
          return res; 
      }
      
      public int findPredecessor(Node node) {
      
           if(node == null) return null;
           if(node->left == null) return null;
           return findMax(node->left);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-14
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多