友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

99. 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?

思路分析

二叉搜索树中序遍历时,就是一个升序排列的序列,在遍历过程中,就可以检查序列的大小。要求使用 O(1) 的空间复杂度,那么只能使用 Morris 遍历。

0099 01
0099 02
0099 03
0099 04
0099 05
0099 06
0099 07
0099 08
0099 09
0099 10
0099 11
  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
 * 使用 Morris 遍历找出错误节点,然后交换其值
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-06-23 22:21:59
 */
public void recoverTree(TreeNode root) {
  if (root == null) return;
  TreeNode curr = root;
  TreeNode mostRight = null;
  TreeNode[] errorNodes = new TreeNode[2];
  TreeNode prior = null;
  while (curr != null) {
    mostRight = curr.left;
    if (mostRight != null) {
      while (mostRight.right != null && mostRight.right != curr) {
        mostRight = mostRight.right;
      }
      if (mostRight.right == null) {
        mostRight.right = curr;
        curr = curr.left;
        continue;
      } else {
        mostRight.right = null;
      }
    }
    if (prior != null) {
      if (prior.val > curr.val) {
        if (errorNodes[0] == null) {
          errorNodes[0] = curr;
          errorNodes[1] = prior;
        } else {
          errorNodes[0] = curr;
        }
      }
    }
    prior = curr;
    curr = curr.right;
  }
  int temp = errorNodes[0].val;
  errorNodes[0].val = errorNodes[1].val;
  errorNodes[1].val = temp;
}