题目

类型:Tree

难度:中等

恢复二叉搜索树 - 图1

解题思路

恢复二叉搜索树 - 图2

代码

  1. class Solution {
  2. public void recoverTree(TreeNode root) {
  3. TreeNode x = null, y = null, pred = null, predecessor = null;
  4. while (root != null) {
  5. if (root.left != null) {
  6. // predecessor 节点就是当前 root 节点向左走一步,然后一直向右走至无法走为止
  7. predecessor = root.left;
  8. while (predecessor.right != null && predecessor.right != root) {
  9. predecessor = predecessor.right;
  10. }
  11. // 让 predecessor 的右指针指向 root,继续遍历左子树
  12. if (predecessor.right == null) {
  13. predecessor.right = root;
  14. root = root.left;
  15. }
  16. // 说明左子树已经访问完了,我们需要断开链接
  17. else {
  18. if (pred != null && root.val < pred.val) {
  19. y = root;
  20. if (x == null) {
  21. x = pred;
  22. }
  23. }
  24. pred = root;
  25. predecessor.right = null;
  26. root = root.right;
  27. }
  28. }
  29. // 如果没有左孩子,则直接访问右孩子
  30. else {
  31. if (pred != null && root.val < pred.val) {
  32. y = root;
  33. if (x == null) {
  34. x = pred;
  35. }
  36. }
  37. pred = root;
  38. root = root.right;
  39. }
  40. }
  41. swap(x, y);
  42. }
  43. public void swap(TreeNode x, TreeNode y) {
  44. int tmp = x.val;
  45. x.val = y.val;
  46. y.val = tmp;
  47. }
  48. }