[LeetCode] Recover Binary Search Tree
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. cocould you devise a constant space solution?
Confused what"{1,#,2,3}"
Means? > Read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '# 'signiies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized
"{1,2,3,#,#,4,#,#,5}"
.
In the middle-order traversal, a List is used to store the positions of each node. Then, the dual pointer is directed from left to right, and the other is directed from right to left to find the wrong position. Then, the values of the connected nodes are exchanged.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution {List
list = new ArrayList<>(); public void recoverTree(TreeNode root) { mid(root); int left = -1; int right = -1; for(int i=0;i
list.get(i+1).val){ left = i; break; } } for(int j=list.size()-1;j>0;j--){ if(list.get(j).val