Restore binary search tree
Title description: Give you the root node root of the binary search tree. Two nodes in the tree have been swapped by mistake. Please restore this tree without changing its structure.
Advanced: The solution using O(n) space complexity is easy to implement. Can you think of a solution that uses only constant space?
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/recover-binary-search-tree/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: recursive method
- First, get all the nodes allNodes of the binary search tree through in-order traversal. Under normal circumstances, if no nodes are incorrectly exchanged, all nodes of allNodes should be arranged in ascending order, so find out the 2 nodes that are exchanged;
- Traverse allNodes from back to front, and find the first node with a smaller value than the previous value, which is the first node high in error;
- From
high-1
traverse allNodes forward and find the first node low with a value smaller than the high node. The node atlow+1
is the wrong second node;- The tree can be restored by swapping the values of the low and high 2 nodes.
import java.util.ArrayList;
import java.util.List;
public class LeetCode_099 {
public static void recoverTree(TreeNode root) {
List<TreeNode> allNodes = inOrder(root);
int high = -1, low = -1;
for (int i = allNodes.size() - 1; i >= 1; i--) {
// 找到上面的要交换的节点
if (allNodes.get(i).val < allNodes.get(i - 1).val) {
high = i;
break;
}
}
// 找到下面要交换的节点
for (low = high - 1; low >= 0; low--) {
if (allNodes.get(low).val < allNodes.get(high).val) {
break;
}
}
low++;
int temp = allNodes.get(low).val;
allNodes.get(low).val = allNodes.get(high).val;
allNodes.get(high).val = temp;
}
/**
* 中序遍历
*
* @param root
* @return
*/
private static List<TreeNode> inOrder(TreeNode root) {
List<TreeNode> nodes = new ArrayList<>();
if (root != null) {
nodes.addAll(inOrder(root.left));
nodes.add(root);
nodes.addAll(inOrder(root.right));
}
return nodes;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(1);
root.right = new TreeNode(4);
root.right.left = new TreeNode(2);
recoverTree(root);
System.out.println("恢复之前");
root.print();
System.out.println();
System.out.println("恢复之后");
root.print();
}
}
【Daily Message】 Thank you for not leaving me, let me know that there are still people who love me. Thank you for your support, no matter how frustrated today, I will still live bravely.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。