LeetCode OJ 99. Recover Binary Search Tree

时间:2023-12-30 17:35:50

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?

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 '#' signifies a path terminator where no node exists below.

Here's an example:

   1
/ \
2 3
/
4
\
5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

Subscribe to see which companies asked this question

先求出树的中序序列,然后在序列中寻找出错的位置。代码如下:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void recoverTree(TreeNode root) {
List<TreeNode> inorder = new ArrayList<TreeNode>();
inOrder(root, inorder); //求中序序列 TreeNode wrong1 = null;
TreeNode wrong2 = null; for(int i = 0; i < inorder.size() - 1; i++){
if(inorder.get(i).val > inorder.get(i+1).val){
if(wrong1 == null){
wrong1 = inorder.get(i);
wrong2 = inorder.get(i+1);
}
else{
wrong2 = inorder.get(i+1);
break;
}
}
}
if(wrong1 != null && wrong2 != null){
int temp = wrong1.val;
wrong1.val = wrong2.val;
wrong2.val = temp;
}
} public void inOrder(TreeNode root, List<TreeNode> inorder){
if(root == null) return;
if(root.left != null) inOrder(root.left, inorder);
inorder.add(root);
if(root.right != null) inOrder(root.right, inorder);
}
}