在BST中,两个节点是随机交换的,我们需要找到这两个节点并将它们交换回去

时间:2012-08-06 08:38:22

标签: algorithm binary-search-tree

给定二叉搜索树,其中交换任意两个节点。所以我们需要找到这两个节点并将它们交换回来(我们需要交换节点,而不是交换数据)

我尝试通过创建一个具有inorder遍历树的附加数组来完成此操作,并将指针保存到每个节点。 然后我们遍历数组并找到不在排序顺序中的两个节点,现在在树中搜索这两个节点然后交换

所以我的问题是如何在O(1)空间中解决这个问题?

3 个答案:

答案 0 :(得分:7)

BST上的

In order traversal会让您对要素进行遍历。
你可以使用有序遍历,找到两个不合适的元素(将它们存储在两个指针中)并交换它们。

这种方法实际上是在不实际创建它的情况下创建你所描述的数组。

但是请注意,空间消耗不是O(1),而是O(h),其中h是树的高度,这是由于堆栈跟踪。如果树是平衡的,它将是O(logn)

答案 1 :(得分:0)

根据BST,可以在O(1)中完成。

例如,如果树的节点有一个指向其父节点的指针,则可以使用维基百科页面的nonRecrusiveInOrderTraversal部分中描述的实现Tree_traversal

另一种可能性是,如果BST存储为一维数组,而不是节点之间的指针,则可以简单地遍历数组(并进行数学运算以确定每个节点的父节点和子节点)。

在进行遍历/遍历时,检查当前元素是否在正确的位置。

如果不是,那么你可以看到树应该在哪里,并与该位置的元素交换。 (如果根位于错误的位置,请注意。)

答案 2 :(得分:0)

我们可以修改下面的isBST()方法来交换那两个随机交换的节点并进行纠正。

/* Returns true if the given tree is a binary search tree
 (efficient version). */
int isBST(struct node* node)
{
  struct node *x = NULL;
  return(isBSTUtil(node, INT_MIN, INT_MAX,&x));
}

/* Returns true if the given tree is a BST and its
   values are >= min and <= max. */
int isBSTUtil(struct node* node, int min, int max, struct node **x)
{

  /* an empty tree is BST */
  if (node==NULL)
     return 1;

  /* false if this node violates the min/max constraint */
  if (node->data < min || node->data > max) {
     if (*x == NULL) {
        *x = node;//same the first incident where BST property is not followed.
     }
     else {
        //here we second node, so swap it with *x.
        int tmp = node->data;
        node->data = (*x)->data;
        (*x)->data = tmp;

     }
     //return 0;
     return 1;//have to return 1; as we are not checking here if tree is BST, as we know it is not BST, and we are correcting it.
  }
  /* otherwise check the subtrees recursively,
   tightening the min or max constraint */
  return
    isBSTUtil(node->left, min, node->data-1, x) &&  // Allow only distinct values
    isBSTUtil(node->right, node->data+1, max, x);  // Allow only distinct values
}