99. Recover Binary Search Tree
阿新 • • 發佈:2018-12-17
Description
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1 / 3 2
Output: [3,1,null,null,2]
3 / 1 2 Example 2:
Input: [3,1,4,null,null,2]
3 / 1 4 / 2
Output: [2,1,4,null,null,3]
2 / 1 4 / 3 Follow up:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
Solution
二叉搜尋樹中兩個節點互換了,恢復。
In-order traversal the tree. find the first element bigger than the node after. and a node smaller than the node ahead of it. Swap these two node.
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode first = null;
TreeNode second = null;
TreeNode prev = new TreeNode(Integer.MIN_VALUE);
public void recoverTree(TreeNode root) {
inOrder(root);
int temp = first.val;
first.val = second.val;
second.val = temp;
}
private void inOrder(TreeNode node){
if (node == null){
return;
}
inOrder(node.left);
if (first == null && prev.val > node.val){
first = prev;
}
if (first != null && prev.val > node.val){
second = node;
}
prev = node;
inOrder(node.right);
}
}
Time Complexity: O(n) Space Complexity: O(1)