题目:
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?题意:
二叉搜索树中有两个元素被错误的交换了
在不改变二叉搜索树结构的前提下,恢复原来的二叉搜索树
注意:
能否只用常数空间来完成呢?
算法分析:
* 例如1,4,3,2,5,6
* 1.当我们读到4的时候,发现是正序的,不做处理
* 2.但是遇到3时,发现逆序,将4存为第一个错误节点,3存为第二个错误节点
* 3.继续往后,发现3,2又是逆序了,那么将第2个错误节点更新为2
* 如果是这样的序列:1,4,3,5,6同上,得到逆序的两个节点为4和3。
* 需要调换的是第一个逆序的第一个元素和第二个逆序的第二个元素
* 中序遍历,遇到每个点,都记录其前驱,记录当前指针cur的前一个节点pre,如果pre.val大于cur.val,表示有错序,多数情况错序有两次;如果有一次错序,说明就是相邻节点需要被交换。
AC代码:
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution
{
TreeNode first = null,second = null,pre = null;
public void recoverTree(TreeNode root)
{
findNode(root);
swap(first, second);
}
private void findNode(TreeNode root)
{
if(root == null)
{
return;
}
if(root.left != null ) findNode(root.left);
if(pre != null && root.val < pre.val)
{
if(first == null)
{
first = pre;
}
second = root;
}
pre = root;
if(root.right != null) findNode(root.right);
}
private void swap(TreeNode node1,TreeNode node2)
{
int tem = node1.val;
node1.val = node2.val;
node2.val = tem;
}
}</span>