LeetCode OJ 99. 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. 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 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.Subscribe to see which companies asked this question
先求出树的中序序列,然后在序列中寻找出错的位置。代码如下:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public void recoverTree(TreeNode root) { 12 List<TreeNode> inorder = new ArrayList<TreeNode>(); 13 inOrder(root, inorder); //求中序序列 14 15 TreeNode wrong1 = null; 16 TreeNode wrong2 = null; 17 18 for(int i = 0; i < inorder.size() - 1; i++){ 19 if(inorder.get(i).val > inorder.get(i+1).val){ 20 if(wrong1 == null){ 21 wrong1 = inorder.get(i); 22 wrong2 = inorder.get(i+1); 23 } 24 else{ 25 wrong2 = inorder.get(i+1); 26 break; 27 } 28 } 29 } 30 if(wrong1 != null && wrong2 != null){ 31 int temp = wrong1.val; 32 wrong1.val = wrong2.val; 33 wrong2.val = temp; 34 } 35 } 36 37 public void inOrder(TreeNode root, List<TreeNode> inorder){ 38 if(root == null) return; 39 if(root.left != null) inOrder(root.left, inorder); 40 inorder.add(root); 41 if(root.right != null) inOrder(root.right, inorder); 42 } 43 }