题目
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?
方法
利用BST中序遍历是一个有序的序列。中序遍历BST,遇到顺序错误的则标记,找到两个错误,交换其值即可。若只找到一个,则说明第一个标记的后面的结点,是错误的。public void recoverTree(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode node = root; TreeNode first = null; TreeNode second = null; TreeNode last = null; while (node != null || !stack.isEmpty()) { while(node != null) { stack.push(node); node = node.left; } TreeNode curNode = stack.pop(); if (last == null) { last = curNode; } else { if (last.val > curNode.val) { if (first == null) { first = last; second = curNode; } else { second = curNode; break; } } last = curNode; } node = curNode.right; } int temp = first.val; first.val = second.val; second.val = temp; }