【LeetCode】 99. Recover Binary Search Tree 恢复二叉搜索树(Hard)(JAVA)
题目地址: https://leetcode.com/problems/recover-binary-search-tree/
题目描述:
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?
题目大意
二叉搜索树中的两个节点被错误地交换。
请在不改变其结构的情况下,恢复这棵树。
解题方法
1、二叉搜索树的前序遍历是一个递增数组
2、错误交换交换的元素和前一个元素必定不是递增的,所以根据前序遍历特性,找出当前元素与前一元素不相同一个或两个点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode pre = null;
TreeNode first = null;
TreeNode second = null;
public void recoverTree(TreeNode root) {
rH(root);
if (first != null && second != null) {
int temp = first.val;
first.val = second.val;
second.val = temp;
}
}
public void rH(TreeNode root) {
if (root == null) return;
rH(root.left);
if (pre != null && root.val < pre.val) {
if (first == null) first = pre;
second = root;
}
pre = root;
rH(root.right);
}
}
执行用时 : 2 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 40.4 MB, 在所有 Java 提交中击败了 12.50% 的用户