繁体   English   中英

以最优方式在二叉搜索树中找到第k个最小元素

[英]Find kth smallest element in a binary search tree in Optimum way

我需要在不使用任何静态/全局变量的情况下找到二叉搜索树中的第 k 个最小元素。 如何高效实现? 我想到的解决方案是在 O(n) 中进行操作,这是最糟糕的情况,因为我计划对整个树进行中序遍历。 但在内心深处,我觉得我没有在这里使用 BST 属性。 我的假设解决方案是正确的还是有更好的解决方案?

这里只是这个想法的概述:

在 BST 中,节点T的左子树仅包含小于存储在T的值的元素。 如果k小于左子树中的元素数,则第k个最小元素必须属于左子树。 否则,如果k较大,则第k个最小元素在右子树中。

我们可以扩充 BST 使其中的每个节点都存储其左子树中元素的数量(假设给定节点的左子树包含该节点)。 有了这条信息,就可以通过反复询问左子树中元素的数量来遍历树,以决定是递归到左子树还是右子树。

现在,假设我们在节点 T:

  1. 如果k == num_elements(T 的左子树) ,那么我们正在寻找的答案是节点T的值。
  2. 如果k > num_elements(T 的左子树) ,那么显然我们可以忽略左子树,因为这些元素也将小于第k个最小的元素。 因此,我们将问题简化为找到k - num_elements(left subtree of T)k - num_elements(left subtree of T)最小元素。
  3. 如果k <num_elements(T的左子树),k个最小的是介于左子树,所以我们减少的问题寻找的k在左子树个最小元素。

复杂度分析:

这需要O(depth of node)时间,在平衡 BST 的最坏情况下为O(log n) ,或者对于随机 BST 平均为O(log n)

一个 BST 需要O(n)存储,并且需要另一个O(n)来存储有关元素数量的信息。 所有的 BST 操作都需要O(depth of node)时间,并且需要O(depth of node)额外的时间来维护用于插入、删除或旋转节点的“元素数量”信息。 因此,在左子树中存储有关元素数量的信息保持了 BST 的空间和时间复杂度。

一个更简单的解决方案是进行中序遍历并跟踪当前要打印的元素(不打印它)。 当我们到达 k 时,打印元素并跳过其余的树遍历。

void findK(Node* p, int* k) {
  if(!p || k < 0) return;
  findK(p->left, k);
  --k;
  if(k == 0) { 
    print p->data;
    return;  
  } 
  findK(p->right, k); 
}
public int ReturnKthSmallestElement1(int k)
    {
        Node node = Root;

        int count = k;

        int sizeOfLeftSubtree = 0;

        while(node != null)
        {

            sizeOfLeftSubtree = node.SizeOfLeftSubtree();

            if (sizeOfLeftSubtree + 1 == count)
                return node.Value;
            else if (sizeOfLeftSubtree < count)
            {
                node = node.Right;
                count -= sizeOfLeftSubtree+1;
            }
            else
            {
                node = node.Left;
            }
        }

        return -1;
    }

这是我基于上述算法在 C# 中的实现只是想我会发布它以便人们可以更好地理解它对我有用

谢谢你

//添加一个没有递归的java版本

public static <T> void find(TreeNode<T> node, int num){
    Stack<TreeNode<T>> stack = new Stack<TreeNode<T>>();

    TreeNode<T> current = node;
    int tmp = num;

    while(stack.size() > 0 || current!=null){
        if(current!= null){
            stack.add(current);
            current = current.getLeft();
        }else{
            current = stack.pop();
            tmp--;

            if(tmp == 0){
                System.out.println(current.getValue());
                return;
            }

            current = current.getRight();
        }
    }
}

一个更简单的解决方案是进行中序遍历并使用计数器 k 跟踪当前要打印的元素。 当我们达到 k 时,打印元素。 运行时间是 O(n)。 记住函数的返回类型不能为void,它必须在每次递归调用后返回其更新后的k值。 一个更好的解决方案是在每个节点都有一个排序的位置值的增强 BST。

public static int kthSmallest (Node pivot, int k){
    if(pivot == null )
        return k;   
    k = kthSmallest(pivot.left, k);
    k--;
    if(k == 0){
        System.out.println(pivot.value);
    }
    k = kthSmallest(pivot.right, k);
    return k;
}

您可以使用迭代中序遍历:http ://en.wikipedia.org/wiki/Tree_traversal#Iterative_Traversal ,在从堆栈中弹出节点后,对第 k 个元素进行简单检查。

带计数器的递归有序遍历

Time Complexity: O( N ), N is the number of nodes
Space Complexity: O( 1 ), excluding the function call stack

这个想法类似于@prasadvk 解决方案,但它有一些缺点(请参阅下面的注释),因此我将其作为单独的答案发布。

// Private Helper Macro
#define testAndReturn( k, counter, result )                         \
    do { if( (counter == k) && (result == -1) ) {                   \
        result = pn->key_;                                          \
        return;                                                     \
    } } while( 0 )

// Private Helper Function
static void findKthSmallest(
    BstNode const * pn, int const k, int & counter, int & result ) {

    if( ! pn ) return;

    findKthSmallest( pn->left_, k, counter, result );
    testAndReturn( k, counter, result );

    counter += 1;
    testAndReturn( k, counter, result );

    findKthSmallest( pn->right_, k, counter, result );
    testAndReturn( k, counter, result );
}

// Public API function
void findKthSmallest( Bst const * pt, int const k ) {
    int counter = 0;
    int result = -1;        // -1 := not found
    findKthSmallest( pt->root_, k, counter, result );
    printf("%d-th element: element = %d\n", k, result );
}

注释(以及与@prasadvk 解决方案的不同之处):

  1. if( counter == k )测试需要在三个地方进行:(a) 左子树之后,(b) 根之后,以及 (c) 右子树之后。 这是为了确保检测到所有位置的第 k 个元素,即不管它位于哪个子树。

  2. if( result == -1 ) test 需要确保只打印结果元素,否则打印从第 k 个最小到根的所有元素。

给定一个普通的二叉搜索树,你所能做的就是从最小的开始,向上遍历以找到正确的节点。

如果您要经常这样做,您可以向每个节点添加一个属性,表示其左子树中有多少个节点。 使用它,您可以将树直接下降到正确的节点。

对于平衡搜索树,它需要O(n)

对于平衡搜索树,在最坏的情况下需要O(k + log n) ,但在摊销意义上只需要O(k)

拥有并管理每个节点的额外整数:子树的大小给出了O(log n) 的时间复杂度。 这种平衡搜索树通常称为RankTree。

一般来说,有解决方案(不基于树)。

问候。

这很有效: status :是保存是否找到元素的数组。 k :是要找到的第 k 个元素。 count :跟踪树遍历期间遍历的节点数。

int kth(struct tree* node, int* status, int k, int count)
{
    if (!node) return count;
    count = kth(node->lft, status, k, count);  
    if( status[1] ) return status[0];
    if (count == k) { 
        status[0] = node->val;
        status[1] = 1;
        return status[0];
    }
    count = kth(node->rgt, status, k, count+1);
    if( status[1] ) return status[0];
    return count;
}

好吧,这是我的 2 美分...

int numBSTnodes(const Node* pNode){
     if(pNode == NULL) return 0;
     return (numBSTnodes(pNode->left)+numBSTnodes(pNode->right)+1);
}


//This function will find Kth smallest element
Node* findKthSmallestBSTelement(Node* root, int k){
     Node* pTrav = root;
     while(k > 0){
         int numNodes = numBSTnodes(pTrav->left);
         if(numNodes >= k){
              pTrav = pTrav->left;
         }
         else{
              //subtract left tree nodes and root count from 'k'
              k -= (numBSTnodes(pTrav->left) + 1);
              if(k == 0) return pTrav;
              pTrav = pTrav->right;
        }

        return NULL;
 }

虽然这绝对不是问题的最佳解决方案,但它是另一种潜在的解决方案,我认为有些人可能会觉得有趣:

/**
 * Treat the bst as a sorted list in descending order and find the element 
 * in position k.
 *
 * Time complexity BigO ( n^2 )
 *
 * 2n + sum( 1 * n/2 + 2 * n/4 + ... ( 2^n-1) * n/n ) = 
 * 2n + sigma a=1 to n ( (2^(a-1)) * n / 2^a ) = 2n + n(n-1)/4
 *
 * @param t The root of the binary search tree.
 * @param k The position of the element to find.
 * @return The value of the element at position k.
 */
public static int kElement2( Node t, int k ) {
    int treeSize = sizeOfTree( t );

    return kElement2( t, k, treeSize, 0 ).intValue();
}

/**
 * Find the value at position k in the bst by doing an in-order traversal 
 * of the tree and mapping the ascending order index to the descending order 
 * index.
 *
 *
 * @param t Root of the bst to search in.
 * @param k Index of the element being searched for.
 * @param treeSize Size of the entire bst.
 * @param count The number of node already visited.
 * @return Either the value of the kth node, or Double.POSITIVE_INFINITY if 
 *         not found in this sub-tree.
 */
private static Double kElement2( Node t, int k, int treeSize, int count ) {
    // Double.POSITIVE_INFINITY is a marker value indicating that the kth 
    // element wasn't found in this sub-tree.
    if ( t == null )
        return Double.POSITIVE_INFINITY;

    Double kea = kElement2( t.getLeftSon(), k, treeSize, count );

    if ( kea != Double.POSITIVE_INFINITY )
        return kea;

    // The index of the current node.
    count += 1 + sizeOfTree( t.getLeftSon() );

    // Given any index from the ascending in order traversal of the bst, 
    // treeSize + 1 - index gives the
    // corresponding index in the descending order list.
    if ( ( treeSize + 1 - count ) == k )
        return (double)t.getNumber();

    return kElement2( t.getRightSon(), k, treeSize, count );
}

签名:

Node * find(Node* tree, int *n, int k);

调用为:

*n = 0;
kthNode = find(root, n, k);

定义:

Node * find ( Node * tree, int *n, int k)
{
   Node *temp = NULL;

   if (tree->left && *n<k)
      temp = find(tree->left, n, k);

   *n++;

   if(*n==k)
      temp = root;

   if (tree->right && *n<k)
      temp = find(tree->right, n, k);

   return temp;
}

Linux Kernel 有一个优秀的增广红黑树数据结构,支持 linux/lib/rbtree.c 中 O(log n) 中的基于秩的操作。

也可以在http://code.google.com/p/refolding/source/browse/trunk/core/src/main/java/it/unibo/refolding/alg/RbTree.java上找到一个非常粗略的 Java 端口,连同 RbRoot.java 和 RbNode.java。 通过调用RbNode.nth(RbNode node, int n),传入树的根,可以得到第n个元素。

这是C#中的简洁版本,它返回第 k 个最小元素,但需要将 k 作为 ref 参数传入(它与@prasadvk 的方法相同):

Node FindSmall(Node root, ref int k)
{
    if (root == null || k < 1)
        return null;

    Node node = FindSmall(root.LeftChild, ref k);
    if (node != null)
        return node;

    if (--k == 0)
        return node ?? root;
    return FindSmall(root.RightChild, ref k);
}

它的O(log n)的寻找最小节点,然后O(K)穿越到k个节点,所以它的O(K + log n)的。

http://www.geeksforgeeks.org/archives/10379

这是这个问题的确切答案:-

1. 在 O(n) 时间使用中序遍历 2. 在 k+log n 时间使用增强树

我找不到更好的算法..所以决定写一个 :) 如果这是错误的,请纠正我。

class KthLargestBST{
protected static int findKthSmallest(BSTNode root,int k){//user calls this function
    int [] result=findKthSmallest(root,k,0);//I call another function inside
    return result[1];
}
private static int[] findKthSmallest(BSTNode root,int k,int count){//returns result[]2 array containing count in rval[0] and desired element in rval[1] position.
    if(root==null){
        int[]  i=new int[2];
        i[0]=-1;
        i[1]=-1;
        return i;
    }else{
        int rval[]=new int[2];
        int temp[]=new int[2];
        rval=findKthSmallest(root.leftChild,k,count);
        if(rval[0]!=-1){
            count=rval[0];
        }
        count++;
        if(count==k){
            rval[1]=root.data;
        }
        temp=findKthSmallest(root.rightChild,k,(count));
        if(temp[0]!=-1){
            count=temp[0];
        }
        if(temp[1]!=-1){
            rval[1]=temp[1];
        }
        rval[0]=count;
        return rval;
    }
}
public static void main(String args[]){
    BinarySearchTree bst=new BinarySearchTree();
    bst.insert(6);
    bst.insert(8);
    bst.insert(7);
    bst.insert(4);
    bst.insert(3);
    bst.insert(4);
    bst.insert(1);
    bst.insert(12);
    bst.insert(18);
    bst.insert(15);
    bst.insert(16);
    bst.inOrderTraversal();
    System.out.println();
    System.out.println(findKthSmallest(bst.root,11));
}

}

这是java代码,

max(Node root, int k) - 找到第 k 个最大的

min(Node root, int k) - 找到第 k 个最小的

static int count(Node root){
    if(root == null)
        return 0;
    else
        return count(root.left) + count(root.right) +1;
}
static int max(Node root, int k) {
    if(root == null)
        return -1;
    int right= count(root.right);

    if(k == right+1)
        return root.data;
    else if(right < k)
        return max(root.left, k-right-1);
    else return max(root.right, k);
}

static int min(Node root, int k) {
    if (root==null)
        return -1;

    int left= count(root.left);
    if(k == left+1)
        return root.data;
    else if (left < k)
        return min(root.right, k-left-1);
    else
        return min(root.left, k);
}

这也行。 只需在树中调用带有 maxNode 的函数

def k_largest(self, node, k): 如果 k < 0 : return None
如果 k == 0: 返回节点 else: k -=1 return self.k_largest(self.predecessor(node), k)

我认为这比接受的答案要好,因为它不需要修改原始树节点来存储其子节点的数量。

我们只需要使用中序遍历从左到右计算最小的节点,当计数等于K时停止搜索。

private static int count = 0;
public static void printKthSmallestNode(Node node, int k){
    if(node == null){
        return;
    }

    if( node.getLeftNode() != null ){
        printKthSmallestNode(node.getLeftNode(), k);
    }

    count ++ ;
    if(count <= k )
        System.out.println(node.getValue() + ", count=" + count + ", k=" + k);

    if(count < k  && node.getRightNode() != null)
        printKthSmallestNode(node.getRightNode(), k);
}

这就是我,但它确实有效。 它将在 o(log n ) 中运行

public static int FindkThSmallestElemet(Node root, int k)
    {
        int count = 0;
        Node current = root;

        while (current != null)
        {
            count++;
            current = current.left;
        }
        current = root;

        while (current != null)
        {
            if (count == k)
                return current.data;
            else
            {
                current = current.left;
                count--;
            }
        }

        return -1;


    } // end of function FindkThSmallestElemet

使用order statistics tree IVlad解决方案是最有效的。 但是,如果您不能使用order statistics tree并且坚持使用常规的旧BST,那么最好的方法是进行Inorder Traversal(如prasadvk所指出的)。 但是如果你想要返回第k个最小元素并且不仅仅是打印出值,那么他的解决方案是不够的。 此外,由于他的解决方案是递归的,因此存在堆栈溢出的危险。 因此,我编写了一个java解决方案,它返回第k个最小节点并使用堆栈来执行In Order Traversal。 运行时间是O(n),而空间复杂度是O(h),其中h是树的最大高度。

// The 0th element is defined to be the smallest element in the tree.
public Node find_kth_element(Node root , int k) {

    if (root == null || k < 0) return null;

    Deque<Node> stack = new ArrayDeque<Node>();
    stack.push(root);

    while (!stack.isEmpty()) {

        Node curr = stack.peek();

        if (curr.left != null) {

            stack.push(curr.left);
            continue;
        }

        if (k == 0) return curr;
        stack.pop();
        --k;

        if (curr.right != null) {

            stack.push(curr.right);

        }

    }

    return null;
}

最好的方法已经存在。但我想为此添加一个简单的代码

int kthsmallest(treenode *q,int k){
int n = size(q->left) + 1;
if(n==k){
    return q->val;
}
if(n > k){
    return kthsmallest(q->left,k);
}
if(n < k){
    return kthsmallest(q->right,k - n);
}

}

int size(treenode *q){
if(q==NULL){
    return 0;
}
else{
    return ( size(q->left) + size(q->right) + 1 );
}}

使用辅助 Result 类来跟踪是否找到节点和当前 k。

public class KthSmallestElementWithAux {

public int kthsmallest(TreeNode a, int k) {
    TreeNode ans = kthsmallestRec(a, k).node;
    if (ans != null) {
        return ans.val;
    } else {
        return -1;
    }
}

private Result kthsmallestRec(TreeNode a, int k) {
    //Leaf node, do nothing and return
    if (a == null) {
        return new Result(k, null);
    }

    //Search left first
    Result leftSearch = kthsmallestRec(a.left, k);

    //We are done, no need to check right.
    if (leftSearch.node != null) {
        return leftSearch;
    }

    //Consider number of nodes found to the left
    k = leftSearch.k;

    //Check if current root is the solution before going right
    k--;
    if (k == 0) {
        return new Result(k - 1, a);
    }

    //Check right
    Result rightBalanced = kthsmallestRec(a.right, k);

    //Consider all nodes found to the right
    k = rightBalanced.k;

    if (rightBalanced.node != null) {
        return rightBalanced;
    }

    //No node found, recursion will continue at the higher level
    return new Result(k, null);

}

private class Result {
    private final int k;
    private final TreeNode node;

    Result(int max, TreeNode node) {
        this.k = max;
        this.node = node;
    }
}
}

好吧,我们可以简单地使用 in order 遍历并将访问过的元素推入堆栈。 弹出 k 次,以获得答案。

我们也可以在 k 个元素之后停止

Python 解决方案时间复杂度:O(n) 空间复杂度:O(1)

想法是使用莫里斯中序遍历

class Solution(object):
def inorderTraversal(self, current , k ):
    while(current is not None):    #This Means we have reached Right Most Node i.e end of LDR traversal

        if(current.left is not None):  #If Left Exists traverse Left First
            pre = current.left   #Goal is to find the node which will be just before the current node i.e predecessor of current node, let's say current is D in LDR goal is to find L here
            while(pre.right is not None and pre.right != current ): #Find predecesor here
                pre = pre.right
            if(pre.right is None):  #In this case predecessor is found , now link this predecessor to current so that there is a path and current is not lost
                pre.right = current
                current = current.left
            else:                   #This means we have traverse all nodes left to current so in LDR traversal of L is done
                k -= 1
                if(k == 0):
                    return current.val
                pre.right = None       #Remove the link tree restored to original here 
                current = current.right
        else:               #In LDR  LD traversal is done move to R 
            k -= 1
            if(k == 0):
                return current.val
            current = current.right

    return 0

def kthSmallest(self, root, k):
    return self.inorderTraversal( root , k  )
public int kthSmallest(TreeNode root, int k) {
     
    LinkedList<TreeNode> stack = new LinkedList<TreeNode>();

    while (true) {
      while (root != null) {
        stack.push(root);
        root = root.left;
      }
      root = stack.pop();
      k = k - 1;
      if (k == 0) return root.val;
      root = root.right;
    }

}     

完整 BST 案例的解决方案:-

Node kSmallest(Node root, int k) {
  int i = root.size(); // 2^height - 1, single node is height = 1;
  Node result = root;
  while (i - 1 > k) {
    i = (i-1)/2;  // size of left subtree
    if (k < i) {
      result = result.left;
    } else {
      result = result.right;
      k -= i;
    }  
  }
  return i-1==k ? result: null;
}

我写了一个简洁的函数来计算第 k 个最小的元素。 我使用有序遍历并在到达第 k 个最小元素时停止。

void btree::kthSmallest(node* temp, int& k){
if( temp!= NULL)   {
 kthSmallest(temp->left,k);       
 if(k >0)
 {
     if(k==1)
    {
      cout<<temp->value<<endl;
      return;
    }

    k--;
 }

 kthSmallest(temp->right,k);  }}
public TreeNode findKthElement(TreeNode root, int k){
    if((k==numberElement(root.left)+1)){
        return root;
    }
    else if(k>numberElement(root.left)+1){
        findKthElement(root.right,k-numberElement(root.left)-1);
    }
    else{
        findKthElement(root.left, k);
    }
}

public int numberElement(TreeNode node){
    if(node==null){
        return 0;
    }
    else{
        return numberElement(node.left) + numberElement(node.right) + 1;
    }
}
public static Node kth(Node n, int k){
    Stack<Node> s=new Stack<Node>();
    int countPopped=0;
    while(!s.isEmpty()||n!=null){
      if(n!=null){
        s.push(n);
        n=n.left;
      }else{
        node=s.pop();
        countPopped++;
        if(countPopped==k){
            return node;
        }
        node=node.right;

      }
  }

}

 public int printInorder(Node node, int k) 
    { 
        if (node == null || k <= 0) //Stop traversing once you found the k-th smallest element
            return k; 

        /* first recur on left child */
        k = printInorder(node.left, k); 

        k--;
        if(k == 0) {  
            System.out.print(node.key);
        }

        /* now recur on right child */
        return printInorder(node.right, k);
    } 

这个java递归算法,一旦找到第k个最小元素就停止递归。

我需要在二进制搜索树中找到第k个最小的元素,而无需使用任何静态/全局变量。 如何有效地做到这一点? 我想到的解决方案是在O(n)中进行操作,这是最糟糕的情况,因为我计划对整个树进行有序遍历。 但在内心深处,我觉得我没有在这里使用BST属性。 我的假设解决方案正确还是有更好的解决方案?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM