Two nodes of a BST are swapped, correct the BST[转载]

Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST.

Input Tree:10/  \5    8/ \2   20In the above tree, nodes 20 and 8 must be swapped to fix the tree.
Following is the output tree10/  \5    20/ \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 is 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 is O(nLogn) and auxiliary space needed is O(n).

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

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

 For example, Nodes 5 and 25 are swapped in {3 5 7 8 10 15 20 25}. The inorder traversal of the given tree is 3 25 7 8 10 15 20 5

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 25 (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 two node’s values.

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

  For example, Nodes 7 and 8 are swapped in {3 5 7 8 10 15 20 25}. The inorder traversal of the given tree is 3 5 8 7 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 will maintain three pointers, first, middle and last. When we find the first point where current node value is smaller than previous node value, we update the first with the previous node & middle with the current node. When we find the second point where current node value is smaller than previous node value, we update the last with the current node. In case #2, we will never find the second point. So, last pointer will not be updated. After processing, if the last node value is null, then two swapped nodes of BST are adjacent.

Following is the implementation of the given code.

  1 // Two 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, pointer to left child
  6    and a pointer to right child */
  7 struct node
  8 {
  9     int data;
 10     struct node *left, *right;
 11 };
 12
 13 // A utility function to swap two integers
 14 void swap( int* a, int* b )
 15 {
 16     int t = *a;
 17     *a = *b;
 18     *b = t;
 19 }
 20
 21 /* Helper function that allocates a new node with the
 22    given data and NULL left and right pointers. */
 23 struct node* newNode(int data)
 24 {
 25     struct node* node = (struct node *)malloc(sizeof(struct node));
 26     node->data = data;
 27     node->left = NULL;
 28     node->right = NULL;
 29     return(node);
 30 }
 31
 32 // This function does inorder traversal to find out the two swapped nodes.
 33 // It sets three pointers, first, middle and last.  If the swapped nodes are
 34 // adjacent to each other, then first and middle contain the resultant nodes
 35 // Else, first and last contain the resultant nodes
 36 void correctBSTUtil( struct node* root, struct node** first,
 37                      struct node** middle, struct node** last,
 38                      struct node** prev )
 39 {
 40     if( root )
 41     {
 42         // Recur for the left subtree
 43         correctBSTUtil( root->left, first, middle, last, prev );
 44
 45         // If this node is smaller than the previous node, it's violating
 46         // the BST rule.
 47         if (*prev && root->data < (*prev)->data)
 48         {
 49             // If this is first violation, mark these two nodes as
 50             // 'first' and 'middle'
 51             if ( !*first )
 52             {
 53                 *first = *prev;
 54                 *middle = root;
 55             }
 56
 57             // If this is second violation, mark this node as last
 58             else
 59                 *last = root;
 60         }
 61
 62         // Mark this node as previous
 63         *prev = root;
 64
 65         // Recur for the right subtree
 66         correctBSTUtil( root->right, first, middle, last, prev );
 67     }
 68 }
 69
 70 // A function to fix a given BST where two nodes are swapped.  This
 71 // function uses correctBSTUtil() to find out two nodes and swaps the
 72 // nodes to fix the BST
 73 void correctBST( struct node* root )
 74 {
 75     // Initialize pointers needed for correctBSTUtil()
 76     struct node *first, *middle, *last, *prev;
 77     first = middle = last = prev = NULL;
 78
 79     // Set the poiters to find out two nodes
 80     correctBSTUtil( root, &first, &middle, &last, &prev );
 81
 82     // Fix (or correct) the tree
 83     if( first && last )
 84         swap( &(first->data), &(last->data) );
 85     else if( first && middle ) // Adjacent nodes swapped
 86         swap( &(first->data), &(middle->data) );
 87
 88     // else nodes have not been swapped, passed tree is really BST.
 89 }
 90
 91 /* A utility function to print Inoder traversal */
 92 void printInorder(struct node* node)
 93 {
 94     if (node == NULL)
 95         return;
 96     printInorder(node->left);
 97     printf("%d ", node->data);
 98     printInorder(node->right);
 99 }
100
101 /* Driver program to test above functions*/
102 int main()
103 {
104     /*   6
105         /  \
106        10    2
107       / \   / \
108      1   3 7  12
109      10 and 2 are swapped
110     */
111
112     struct node *root = newNode(6);
113     root->left        = newNode(10);
114     root->right       = newNode(2);
115     root->left->left  = newNode(1);
116     root->left->right = newNode(3);
117     root->right->right = newNode(12);
118     root->right->left = newNode(7);
119
120     printf("Inorder Traversal of the original tree \n");
121     printInorder(root);
122
123     correctBST(root);
124
125     printf("\nInorder Traversal of the fixed tree \n");
126     printInorder(root);
127
128     return 0;
129 }

转载于:https://www.cnblogs.com/harvyxu/p/7795499.html

Two nodes of a BST are swapped, correct the BST相关推荐

  1. Two nodes of a BST are swapped, correct the BST(恢复两个节点被交换的BST)

    Two nodes of a BST are swapped, correct the BST(恢复两个节点被交换的BST) Q: BST的两个节点被交换了,修复它: Input Tree:10/ \ ...

  2. 【Java数据结构】BST树(二叉搜索树)总结03(求BST树高度,求BST树节点个数)

    二叉树总结:入口 二叉树的基本操作: 1.插入,删除 操作 2.前.中.后序遍历,层序遍历 3.求BST树高度,求BST树节点个数 4.返回中序遍历第k个节点的值 5.判断一个二叉树是否是BST树,判 ...

  3. bst 删除节点_在BST中删除大于或等于k的节点

    bst 删除节点 Problem statement: 问题陈述: Given a BST and a value x, write a function to delete the nodes ha ...

  4. 二叉搜索树bst_二进制搜索树(BST)–搜索插入和删除

    二叉搜索树bst In this tutorial, we'll be discussing the Binary Search Tree Data Structure. We'll be imple ...

  5. 【每日一算法】两数之和 IV - 输入 BST

    微信改版,加星标不迷路! 每日一算法-两数之和IV-输入BST 作者:阿广 阅读目录 1 题目 2 解析 1 题目 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目 ...

  6. AVL树:解决BST可能导致的长链问题

    BST存在的问题 BST的性质有可能导致所有的数据都插在了同一个链路上,导致没有一个节点有左子树,都是右子树,像是一个链表,失去了它的lgn的性质 AVL的性质 AVL是作者的名字缩写 每个左子树的高 ...

  7. Algorithm:树相关算法(BBT/BST/B树/R树)简介(二叉查找树、二叉查找树的插入节点、二叉查找树的删除、二叉树的遍历、平衡二叉树)C 语言实现

    Algorithm:树相关算法(BBT/BST/B树/R树)简介(二叉查找树.二叉查找树的插入节点.二叉查找树的删除.二叉树的遍历.平衡二叉树)C++语言实现 目录 树的基础知识 1.二叉树的遍-前序 ...

  8. 看动画学算法之:二叉搜索树BST

    文章目录 简介 BST的基本性质 BST的构建 BST的搜索 BST的插入 BST的删除 看动画学算法之:二叉搜索树BST 简介 树是类似于链表的数据结构,和链表的线性结构不同的是,树是具有层次结构的 ...

  9. 有序二叉树c语言,二叉搜索树(BST)的实现(C语言)(原创)

    叉搜索树(Binary Search Tree)的一般形式如下图所示,每个节点中的元素大于它的左子树中的所有元素,小于它的右子树中的所有元素.对该图中的二叉树进行中序遍历得到一个从小到大排列的有序序列 ...

最新文章

  1. Android 自定义view时用到的TypedArray
  2. nginx Win下实现简单的负载均衡(2)站点共享Session
  3. c语言中常用的程序,C语言一些常用语句
  4. emulator: ERROR: x86 emulation currently requires hardware acceleration!
  5. 值得向IOS学习的15个APP设计技巧!
  6. [bzoj3489]A simple rmq problem
  7. Nodejs中的模块系统
  8. flask执行python脚本_如何在Flask中运行python脚本
  9. Emlog使用qq头像作为评论头像
  10. 数据结构分类概述【转载】
  11. swift中的只读属性实现,很简单
  12. excel如何晒出重复数据_3秒找出Excel中的重复数据,年底数据统计用得上,赶紧码住...
  13. 比rufus/scheduler更独立简洁的定时脚本必备whenever
  14. redis mysql 雪崩_Redis雪崩和穿透问题
  15. dfs之解救小哈-c语言
  16. requests框架详解
  17. 屠龙传说世界【全自动】辅助脚本
  18. pla3d打印材料密度_3D打印材料:PLA (聚乳酸)材料
  19. 原始套接字的花花世界
  20. webqq 机器人 java_跨平台QQ客户端iQQ 根据WebQQ3.0协议Java开发

热门文章

  1. MongoDB查询命令
  2. “教练,我想打篮球“ —— 给做系统的同学们准备的 AI 学习系列小册
  3. android 设置电池状态
  4. 温州计算机职高学校排名,温州职高排名及分数线 2020最新排名
  5. 华为在发布会带来了harmonyos,华为HarmonyOS 2.0正式发布,共赢移动终端产业的下一个十年...
  6. 玩手游哪款蓝牙耳机续航高?2020新款高人气蓝牙耳机推荐
  7. 4.5清明节写个三角形吧
  8. SNPE分析与评测 (1)
  9. Easy AR通过Http协议上传本地图片至云图库
  10. 小程序X及以上机型刘海及底部条css获取距离