1. https://leetcode.com/mockinterview/session/result/xyc51it/
    https://leetcode.com/problems/recover-binary-search-tree/
  2.  
  3. // 想到了Space O(N)的解法:方法是直接将BST放平,然后重新排序,然后比较一下就可以。
    // 原题中提到说,有 Space O(Constant)的方法,还要研究一下
  4.  
  5. 看了Discuss,也上网搜了一下,发现空间O(1)可以用 Morris遍历的方法。单独写了一篇博客,方法介绍如下:
    http://www.cnblogs.com/charlesblc/p/6013506.html
  1. 下面是leetcode这道题目我的解答。没有使用O(1)空间复杂度,使用了O(n)空间复杂度。 还用到了Java里面 Arrays.sort方法,也需要注意toArray函数的参数。
  2.  
  3. 除了这种解法,还有一种,是我之前做的方法,也很好,通过两个数字记录可能出错的位置,很巧妙,在这个后面给出。
  1. package com.company;import java.util.*;
  2.  
  3. class TreeNode {
  4. int val;
  5. TreeNode left;
  6. TreeNode right;
  7. TreeNode(int x) { val = x; }
  8. }
  9.  
  10. class StkNode {
  11. TreeNode tn;
  12. int count;
  13. StkNode(TreeNode tn) {
  14. this.tn = tn;
  15. count = 0;
  16. }
  17. }
  18.  
  19. class Solution {
  20.  
  21. List<Integer> getArray(TreeNode root) {
  22.  
  23. List<Integer> ret = new ArrayList<>();
  24. if (root.left != null) {
  25. ret.addAll(getArray(root.left));
  26. }
  27. ret.add(root.val);
  28. if (root.right != null) {
  29. ret.addAll(getArray(root.right));
  30. }
  31. return ret;
  32. }
  33.  
  34. public void recoverTree(TreeNode root) {
  35.  
  36. // Space O(N)的解法,想到了是直接将BST放平,然后重新排序,然后比较一下就可以。
  37.  
  38. // 分情况, 左ok, 右ok, 1. 上ok, 2. 上不ok
  39. // 左不ok, 或者右不ok, 1. 上ok,
  40. // 想不清楚,先用直接的方法:
  41. if (root == null) {
  42. return;
  43. }
  44. List<Integer> ret = getArray(root);
  45. Integer[] sortRet= ret.toArray(new Integer[0]);
  46. Arrays.sort(sortRet);
  47.  
  48. int[] change = new int[2];
  49. int[] index = new int[2];
  50. int ii = 0;
  51. for (int i=0; i<sortRet.length; i++) {
  52. //System.out.printf("old: %d, new: %d\n", ret.get(i), sortRet[i]);
  53. if (ret.get(i) != sortRet[i]) {
  54. index[ii] = i+1;
  55. change[ii] = sortRet[i];
  56. ii++;
  57. if (ii >= 2) {
  58. break;
  59. }
  60. }
  61. }
  62. //System.out.printf("ii:%d\n", ii);
  63.  
  64. Stack<StkNode> stk = new Stack<>();
  65. int count = 0;
  66. int k = 0;
  67. StkNode stkRoot = new StkNode(root);
  68. stk.push(stkRoot);
  69. while (!stk.isEmpty()) {
  70. StkNode tmp = stk.pop();
  71. //System.out.printf("here: %d, %d, %d\n", tmp.count, count, tmp.tn.val);
  72. if (tmp.count == 1) {
  73. count++;
  74. if (count == index[k]) {
  75. //System.out.printf("here: %d\n", count);
  76. tmp.tn.val = change[k];
  77. k++;
  78. if (k>=2) {
  79. return;
  80. }
  81. }
  82. if (tmp.tn.right != null) {
  83. StkNode newTmp = new StkNode(tmp.tn.right);
  84. stk.push(newTmp);
  85. }
  86. }
  87. else {
  88. tmp.count++;
  89. stk.push(tmp);
  90. if (tmp.tn.left != null) {
  91. StkNode newTmp = new StkNode(tmp.tn.left);
  92. stk.push(newTmp);
  93. }
  94. }
  95. }
  96.  
  97. }
  98. }
  99.  
  100. public class Main {
  101.  
  102. public static void main(String[] args) {
  103. System.out.println("Hello!");
  104. Solution solution = new Solution();
  105.  
  106. TreeNode root = new TreeNode(2);
  107. TreeNode root2 = new TreeNode(3);
  108. TreeNode root3 = new TreeNode(1);
  109. root.left = root2;
  110. root.right = root3;
  111. solution.recoverTree(root);
  112. System.out.printf("Get ret: \n");
  113. System.out.printf("Get ret1: %d\n", root.left.val);
  114. System.out.printf("Get ret2: %d\n", root.val);
  115. System.out.printf("Get ret3: %d\n", root.right.val);
  116. System.out.println();
  117.  
  118. /*Iterator<List<Integer>> iterator = ret.iterator();
  119. while (iterator.hasNext()) {
  120. Iterator iter = iterator.next().iterator();
  121. while (iter.hasNext()) {
  122. System.out.printf("%d,", iter.next());
  123. }
  124. System.out.println();
  125. }*/
  126.  
  127. System.out.println();
  128.  
  129. }
  130. }

下面我之前的解法,也很好,通过两个数字来记录可能的出错位置,并且在遍历的同时,更新这个位置。需要对出错的规律有深刻了解,比如在解法中,first_result位置就始终没有变过,因为一旦找到就可以不变,通过second_result位置的改变,就能满足条件:

  1. https://leetcode.com/problems/recover-binary-search-tree/
  2.  
  3. /**
  4. * Definition for a binary tree node.
  5. * struct TreeNode {
  6. * int val;
  7. * TreeNode *left;
  8. * TreeNode *right;
  9. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  10. * };
  11. */
  12. class Solution {
  13. stack < pair <TreeNode*, int> > stk;
  14. public:
  15. void recoverTree(TreeNode* root) {
  16. if (root == NULL) {
  17. return;
  18. }
  19. pair<TreeNode*, int> pr(root, 0);
  20. stk.push(pr);
  21.  
  22. TreeNode * first_result = NULL;
  23. TreeNode * last_result = NULL;
  24. TreeNode* last = NULL;
  25.  
  26. pair<TreeNode*, int> tmp;
  27. TreeNode* tn_tmp;
  28.  
  29. while ( !stk.empty() ) {
  30. tmp = stk.top();
  31. stk.pop();
  32.  
  33. if (tmp.second == 0) {
  34. // left
  35. tn_tmp = tmp.first;
  36. pair<TreeNode*, int> tmp_cur(tn_tmp, 1);
  37. stk.push(tmp_cur);
  38.  
  39. if (tn_tmp->left != NULL) {
  40. pair<TreeNode*, int> tmp_left(tn_tmp->left, 0);
  41. stk.push(tmp_left);
  42. }
  43.  
  44. }
  45. else {
  46. // right
  47. tn_tmp = tmp.first;
  48. if (last != NULL && last->val > tn_tmp->val) {
  49. // Found
  50. if (first_result == NULL ) {
  51. first_result = last;
  52. last_result = tn_tmp;
  53. }
  54. else {
  55. last_result = tn_tmp;
  56. break;
  57. }
  58. }
  59. last = tn_tmp;
  60.  
  61. if (tn_tmp->right != NULL) {
  62. pair<TreeNode*, int> tmp_pr(tn_tmp->right, 0);
  63. stk.push(tmp_pr);
  64. }
  65.  
  66. }
  67.  
  68. }
  69.  
  70. if (first_result != NULL && last_result != NULL) {
  71. int swap = first_result->val;
  72. first_result->val = last_result->val;
  73. last_result->val = swap;
  74. }
  75. return;
  76.  
  77. }
  78.  
  79. };

好!recover-binary-search-tree(难)& 两种好的空间O(n)解法 & 空间O(1)解法的更多相关文章

  1. [LeetCode] Validate Binary Search Tree (两种解法)

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  2. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  3. 【LeetCode练习题】Recover Binary Search Tree

    Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recove ...

  4. LeetCode: Recover Binary Search Tree 解题报告

    Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recove ...

  5. [LeetCode] 99. Recover Binary Search Tree(复原BST) ☆☆☆☆☆

    Recover Binary Search Tree leetcode java https://leetcode.com/problems/recover-binary-search-tree/di ...

  6. [线索二叉树] [LeetCode] 不需要栈或者别的辅助空间,完成二叉树的中序遍历。题:Recover Binary Search Tree,Binary Tree Inorder Traversal

    既上篇关于二叉搜索树的文章后,这篇文章介绍一种针对二叉树的新的中序遍历方式,它的特点是不需要递归或者使用栈,而是纯粹使用循环的方式,完成中序遍历. 线索二叉树介绍 首先我们引入“线索二叉树”的概念: ...

  7. 【LeetCode】99. Recover Binary Search Tree

    Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recove ...

  8. 【LeetCode】99. Recover Binary Search Tree 解题报告(Python)

    [LeetCode]99. Recover Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/p ...

  9. 【leetcode】Recover Binary Search Tree

    Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recove ...

  10. 39. Recover Binary Search Tree && Validate Binary Search Tree

    Recover Binary Search Tree OJ: https://oj.leetcode.com/problems/recover-binary-search-tree/ Two elem ...

随机推荐

  1. 深入mysql_fetch_row()与mysql_fetch_array()的区别详解

    这两个函数,返回的都是一个数组,区别就是第一个函数返回的数组是只包含值,我们只能$row[0],$row[1],这样以数组下标来读取数据,而mysql_fetch_array()返回的数组既包含第一种 ...

  2. Ubuntu实用快捷键

    ALT + TAB: 切换程序窗口Win+w: 显示所有的工作空间,可轻松进行切换 ===== Terminal终端 ===== CTRL + ALT + T: 打开终端 TAB: 自动补全命令或文件 ...

  3. Caffe安装教程(原创)

    转载请注明地址 说明:本文档参考自Caffe官网的安装说明,http://caffe.berkeleyvision.org/installation.html 如果对安装过程中,需要用到的依赖不明,请 ...

  4. Hibernate各种主键生成策略与配置详解【附1--<generator class="foreign">】

    1.assigned 主键由外部程序负责生成,在 save() 之前必须指定一个.Hibernate不负责维护主键生成.与Hibernate和底层数据库都无关,可以跨数据库.在存储对象前,必须要使用主 ...

  5. Leetcode#143 Reorder List

    原题地址 先把链表分割成前后两半,然后交叉融合 实践证明,凡是链表相关的题目,都应该当成工程类题目做,局部变量.功能函数什么的随便整,代码长了没关系,关键是清楚,不容易出错. 代码: ListNode ...

  6. xargs 加 gm批量转换图片

    %x50% @ ../-\ 南澳西涌_50%/@ 看了很多说明上都在用-i,这是一个已经废弃了的参数

  7. Feature Flag

    know more from here: https://www.youtube.com/watch?v=WMRjj06R6jg&list=UUkQX1tChV7Z7l1LFF4L9j_g F ...

  8. hdu 1233 还是畅通工程(最小生成树,基础)

    题目 //也是标准的最小生成树啊,我就改一点点,不重新再打一遍增加熟练度了 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #inclu ...

  9. [SQL Server系] -- 约束

    什么是约束? 约束(Constraint)是SQL Server中提供的 自动保存数据库完整性 的一种方法,定义了可输入表或表的列中的数据限制条件. SQL Server中共有5中约束 PRIMARY ...

  10. addListener添加事件监听器,第三个参数useCapture (Boolean) 的作用

    addEventListener 有三个参数:第一个参数表示事件名称(不含 on,如 "click"):第二个参数表示要接收事件处理的函数:第三个参数为 useCapture,本文 ...