如何在二叉搜索树中查找交换节点?

时间:2012-09-04 11:04:08

标签: c algorithm

这是一个面试问题。

给出了二叉搜索树,并且交换了两个节点的值。问题是如何在树的单次遍历中找到节点和交换值?

我试图使用下面的代码解决这个问题,但我无法阻止递归,所以我得到分段错误。帮助我如何阻止递归。

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdlib.h>

 /* A binary tree node has data, pointer to left child
 and a pointer to right child */
 struct node
{
 int data;
 struct node* left;
 struct node* right;
};
/* Helper function that allocates a new node with the
 given data and NULL left and right pointers. */
 struct node* newNode(int data)
 {
  struct node* node = (struct node*)
                    malloc(sizeof(struct node));
 node->data = data;
 node->left = NULL;
 node->right = NULL;
 return(node);
 }
void modifiedInorder(struct node *root, struct node **nextNode)
 {
    static int nextdata=INT_MAX;
    if(root)
    {       
        modifiedInorder(root->right, nextNode);
        if(root->data > nextdata)
        return;
        *nextNode = root;
        nextdata = root->data;

        modifiedInorder(root->left, nextNode);          
    }
}

void inorder(struct node *root, struct node *copyroot, struct node **prevNode)
{
    static int prevdata = INT_MIN; 
    if(root)
    {
        inorder(root->left, copyroot, prevNode);
        if(root->data < prevdata)
        {
            struct node *nextNode = NULL;
            modifiedInorder(copyroot, &nextNode);

            int data = nextNode->data;
            nextNode->data = (*prevNode)->data;
            (*prevNode)->data = data;
            return;
        }
        *prevNode = root;
        prevdata = root->data;
        inorder(root->right, copyroot, prevNode);           
    }
}

/* Given a binary tree, print its nodes in inorder*/
void printInorder(struct node* node)
{
    if (node == NULL)
        return;

    /* first recur on left child */
    printInorder(node->left);

    /* then print the data of node */
    printf("%d ", node->data);

    /* now recur on right child */
    printInorder(node->right);
}


int main()
{
    /*   4
        /  \
       2    3
      / \
     1   5
    */

    struct node *root = newNode(1);  // newNode will return a node.
    root->left        = newNode(2);
    root->right       = newNode(3);
    root->left->left  = newNode(4);
    root->left->right = newNode(5);
    printf("Inorder Traversal of the original tree\n ");
    printInorder(root);

    struct node *prevNode=NULL;
    inorder(root, root, &prevNode);

    printf("\nInorder Traversal of the fixed tree \n");
    printInorder(root);

    return 0;

}

5 个答案:

答案 0 :(得分:7)

使用inorder遍历走到树上。通过使用它,您将获得所有元素的排序,并且将交换一个比周围元素更大的元素。

例如,请考虑以下二叉树

          _  20  _
         /         \
      15             30
     /   \         /   \ 
   10    17      25     33
  / |   /  \    /  \    |  \
9  16  12  18  22  26  31  34

首先,我们将其线性化为数组,然后得到

9 10 16 15 12 17 18 20 22 25 26 30 31 33 34

现在您可以注意到16大于其周围元素,并且12小于它们。这立刻告诉我们交换了12和16。

答案 1 :(得分:1)

以下函数通过在收紧边界的同时递归迭代左右子树来验证树是否为BST。

我认为可以修改它以通过

实现上述任务
  1. 不是返回false,而是返回temp,即指向未使树成为BST的节点的指针。
  2. 会有两个这样的实例同时给出两个交换值。
  3. 编辑:我们需要区分递归函数返回true与指向交换节点的指针

    这假定问题定义中只提到了两个这样的值

    bool validate_bst(tnode *temp, int min, int max)
    {
            if(temp == NULL)
                    return true;
    
            if(temp->data > min && temp->data < max)
            {
                    if( validate_bst(temp->left, min, temp->data) && 
                        validate_bst(temp->right, temp->data, max) )
                            return true;
            }
    
            return false;
    }
    

    主要会像上面这样呼叫api

       validate_bst(root, -1, 100); // Basically we pass -1 as min and 100 as max in
                                         // this instance
    

答案 2 :(得分:1)

我们可以在O(n)时间内解决此问题,并且只需遍历给定的BST。由于BST的有序遍历始终是一个有序数组,因此可以将问题简化为交换有序数组的两个元素的问题。我们需要处理两种情况:

      6 
    /  \ 
   10    2 
  / \   / \ 
 1   3 7  12 

1。交换的节点在BST的顺序遍历中不相邻。

例如,节点10和2在{1 10 3 6 7 2 12}中交换。 给定树的有序遍历为1 10 3 6 7 2 12

如果我们仔细观察,在有序遍历期间,我们发现节点3小于先前访问的节点10。这里保存了节点10(先前的节点)的上下文。同样,我们发现节点2小于先前的节点7。这次,我们保存了节点2(当前节点)的上下文。最后交换两个节点的值。

2。交换的节点在BST的有序遍历中是相邻的。

      6 
    /  \ 
   10    8 
  / \   / \ 
 1   3 7  12 

例如,节点10和2在{1 10 3 6 7 8 12}中交换。 给定树的有序遍历为1 10 3 6 7 8 12 与情况#1不同,此处仅存在一个节点值小于先前节点值的点。例如节点10小于节点36。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void recoverTreeUtil(TreeNode *root, TreeNode **first, TreeNode **middle, TreeNode **last, TreeNode **prev) {
        if (root) {
            recoverTreeUtil(root->left, first, middle, last, prev);
            if (*prev && (*prev)->val > root->val) {
                if (!(*first)) {
                    *first = *prev;
                    *middle = root;
                } else *last = root;
            }
            *prev = root;
            recoverTreeUtil(root->right, first, middle, last, prev);
        }
    }
    void recoverTree(TreeNode* root) {
        TreeNode *first, *middle, *last, *prev;
        first = middle = last = prev = nullptr;
        recoverTreeUtil(root, &first, &middle, &last, &prev);
        if (first && last) swap(first->val, last->val);
        else if (first && middle) swap(first->val, middle->val);
    }
};

答案 3 :(得分:0)

我在Geeksforgeeks.com上找到了这个问题的另一个解决方案..............各位你们可以查看这个帖子,以获得下面代码的更多解释http://www.geeksforgeeks.org/archives/23616

// Two nodes in the BST's swapped, correct the BST.
#include <stdio.h>
#include <stdlib.h>

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node *left, *right;
};

// A utility function to swap two integers
void swap( int* a, int* b )
{
int t = *a;
*a = *b;
*b = t;
}

/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node *)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}

// This function does inorder traversal to find out the two swapped nodes.
// It sets three pointers, first, middle and last.  If the swapped nodes are
// adjacent to each other, then first and middle contain the resultant nodes
// Else, first and last contain the resultant nodes
void correctBSTUtil( struct node* root, struct node** first,
                 struct node** middle, struct node** last,
                 struct node** prev )
{
if( root )
{
    // Recur for the left subtree
    correctBSTUtil( root->left, first, middle, last, prev );

    // If this node is smaller than the previous node, it's violating
    // the BST rule.
    if (*prev && root->data < (*prev)->data)
    {
        // If this is first violation, mark these two nodes as
        // 'first' and 'middle'
        if ( !*first )
        {
            *first = *prev;
            *middle = root;
        }

        // If this is second violation, mark this node as last
        else
            *last = root;
    }

    // Mark this node as previous
    *prev = root;

    // Recur for the right subtree
    correctBSTUtil( root->right, first, middle, last, prev );
}
}

// A function to fix a given BST where two nodes are swapped.  This
// function uses correctBSTUtil() to find out two nodes and swaps the
// nodes to fix the BST
void correctBST( struct node* root )
{
// Initialize pointers needed for correctBSTUtil()
struct node *first, *middle, *last, *prev;
first = middle = last = prev = NULL;

// Set the poiters to find out two nodes
correctBSTUtil( root, &first, &middle, &last, &prev );

// Fix (or correct) the tree
if( first && last )
    swap( &(first->data), &(last->data) );
else if( first && middle ) // Adjacent nodes swapped
    swap( &(first->data), &(middle->data) );

// else nodes have not been swapped, passed tree is really BST.
}

/* A utility function to print Inoder traversal */
void printInorder(struct node* node)
{
if (node == NULL)
    return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}

/* Driver program to test above functions*/
int main()
{
/*   6
    /  \
   10    2
  / \   / \
 1   3 7  12
 10 and 2 are swapped
*/

struct node *root = newNode(6);
root->left        = newNode(10);
root->right       = newNode(2);
root->left->left  = newNode(1);
root->left->right = newNode(3);
root->right->right = newNode(12);
root->right->left = newNode(7);

printf("Inorder Traversal of the original tree \n");
printInorder(root);

correctBST(root);

printf("\nInorder Traversal of the fixed tree \n");
printInorder(root);

return 0;
}
Output:

 Inorder Traversal of the original tree
 1 10 3 6 7 2 12
 Inorder Traversal of the fixed tree
 1 2 3 6 7 10 12
 Time Complexity: O(n)

有关更多测试用例,请参阅此链接http://ideone.com/uNlPx

答案 4 :(得分:-1)

我的C ++解决方案:

struct node *correctBST( struct node* root )
{
//add code here.
    if(!root)return root;
    struct node* r = root;
    stack<struct node*>st;
   // cout<<"1"<<endl;
    struct node* first = NULL;
    struct node* middle = NULL;
    struct node* last = NULL;
    struct node* prev = NULL; 
    while(root  || !st.empty()){
        while(root){
            st.push(root);
            root = root->left;
        }
        root = st.top();
        st.pop();
        if(prev && prev->data > root->data){
            if(!first){
                first = prev;
                middle = root;
            }
            else{
                last = root;
            }
        }
        prev = root;
        root = root->right;
    }
    if(first && last){
        swap(first->data,last->data);
    }
    else{
        swap(first->data,middle->data);
    }
    return r;
}