Nodes of a BST is swapped, correct the BST

Source: Internet
Author: User

Nodes of a BST is swapped, correct the bst[reprint]

The nodes of a Binary Search Tree (BST) is swapped. Fix (or correct) the BST.

Input Tree:         5    8      /      2   20In The above Tree, nodes and 8 must be swapped to fix the tree.< C8/>following is the output tree        /         5      /      2   8
Recommended:please Solve it On "Practice"First, before moving on to the solution.

The inorder traversal of a BST produces a sorted array. So a simple method was to store inorder traversal of the input tree in an auxiliary array. Sort the auxiliary array. Finally, insert the auxiilary array elements back to the BST, keeping the structure of the BST same. Time complexity of this method was O (NLOGN) and auxiliary space needed is O (n).

We can solve this at O (n)time and with a single traversal of the given BST. Since inorder traversal of BST are always a sorted arrays, the problem can be reduced to a problem where the elements of a s Orted array is swapped. There is cases that we need to handle:

1. The swapped nodes is not adjacent in the inorder traversal of the BST.

For example, Nodes 5 and is swapped in {3 5 7 8 10 15 20 25}.  

If we observe carefully, during inorder traversal, we find node 7 is smaller than the previous visited node 25. Here Save the context of node (previous node). Again, we find that node 5 is smaller than the previous node 20. This time, we save the context of node 5 (current node). Finally swap the Both node ' s values.

2. The swapped nodes is adjacent in the inorder traversal of BST.

  For example, Nodes 7 and 8 is swapped in {3 5 7 8 10 15 20 25}.   

Unlike case #1, here only one point exists where a node value is smaller than previous node value. e.g. node 7 is smaller than node 8.

How to Solve? We'll maintain three pointers, first, middle and last. When we find the first point where current node value was smaller than previous node value, we update the first with the PR Evious node & Middle with the current node. When we find the second point where current node value was smaller than previous node value, we update the last with the CU Rrent node. In case #2, we'll never find the second point. So, the last pointer won't be updated. After processing, if the last node value was null, then the swapped nodes of BST was adjacent.

Following is the implementation of the given code.

1 //nodes in the BST ' s swapped, correct the BST.2#include <stdio.h>3#include <stdlib.h>4  5 /*A Binary tree node has data, pointer6 And a pointer to right child*/7 structnode8 {9     intdata;Ten     structNode *left, *Right ; One }; A   - //A utility function to swap integers - voidSwapintBint*b) the { -     intt = *A; -*a = *b; -*b =T; + } -   + /*Helper function that allocates a new node with the A given data and NULL left and right pointers.*/ at structnode* NewNode (intdata) - { -     structnode* node = (structNode *)malloc(sizeof(structnode)); -Node->data =data; -Node->left =NULL; -Node->right =NULL; in     return(node); - } to   + //This function does inorder traversal to find out the swapped nodes. - //It sets three pointers, first, middle and last. If the swapped nodes is the //adjacent to all other, then first and middle contain the resultant nodes * //Else, first and last contain the resultant nodes $ voidCorrectbstutil (structnode* Root,structnode**First ,Panax Notoginseng                      structnode** Middle,structnode**Last , -                      structnode**prev) the { +     if(Root) A     { the         //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) -         { the             //If This is first violation, mark these, and nodes as -             //' first ' and ' Middle 'Wuyi             if( !*First ) the             { -*first = *prev; Wu*middle =Root; -             } About   $             //If This was second violation, mark this node as last -             Else -*last =Root; -         } A   +         //Mark This node as previous the*prev =Root; -   $         //recur for the right subtree theCorrectbstutil (root->Right , first, middle, last, prev); the     } the } the   - //a function to fix a given BST where the nodes is swapped. this in //function uses Correctbstutil () to find out both nodes and swaps the the //nodes to fix the BST the voidCorrectbst (structnode*root) About { the     //Initialize pointers needed for Correctbstutil () the     structNode *first, *middle, *last, *prev; theFirst = middle = last = prev =NULL; +   -     //Set the poiters to find out nodes theCorrectbstutil (Root, &first, &middle, &last, &prev);Bayi   the     //Fix (or correct) the tree the     if(First &&Last ) -Swap (& (First->data), & (last->data)); -     Else if(First && middle)//adjacent nodes swapped theSwap (& (First->data), & (middle->data)); the   the     //else nodes has not been swapped, passed tree is really BST. the } -   the /*A utility function to print Inoder traversal*/ the voidPrintinorder (structnode*node) the {94     if(node = =NULL) the         return; thePrintinorder (node->Left ); theprintf"%d", node->data);98Printinorder (node->Right ); About } -  101 /*Driver program to test above functions*/102 intMain ()103 {104     /*6 the         /  106 Ten 2107       / \   / 108 1 3 7109 Ten and 2 are swapped the     */111   the     structNode *root = NewNode (6);113Root->left = NewNode (Ten); theRoot->right = NewNode (2); theRoot->left->left = NewNode (1); theRoot->left->right = NewNode (3);117Root->right->right = NewNode ( A);118Root->right->left = NewNode (7);119   -printf"inorder traversal of the original tree \ n");121 Printinorder (root);122  123 Correctbst (root);124   theprintf"\ninorder traversal of the fixed tree \ n");126 Printinorder (root);127   -     return 0;129}

Nodes of a BST is swapped, correct the BST

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.