Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
一棵二叉搜索树,有两个节点换过来了,需要找出这两个节点,换回来。
我们发现,一棵完好的BST,它的中序遍历是一个有序的数组n。
从左往右找到第一个n[i-1] >n[i], n[i-1]为第一个错误节点。 从右往左找到第一个n[i+1] < n[i], n[i+1]为第二个错误节点,也就是从左往右找到最后一个n[i-1]>n[i], n[i]为第二个错误节点。
新闻热点
疑难解答