/* * 99. Recover Binary Search Tree * 2016-5-14 By Mingyang * inorder,开始是网上的代码,inorder的dfs方法 * 后面自己借鉴了isValidBST的思路,自己写的代码,用stack来做 * 第一种该方法需要把几个变量设为全局变量 * 一个容易错误的地方就是在找到第一个mismatch地方时候,需要把pre赋予first * 把现在的root赋予second,因为两个mismatch可能就是这两个交换了啊, * 如果后面还有second的话还可以交换second的信息。 */ static TreeNode pre; static TreeNode first; static TreeNode second; public static void inorder(TreeNode root) { if (root == null) return; inorder(root.left); if (pre == null) {// 只有一种情况,就是最初的情况,最开始的最左边的值-----convert BST to double // linked list pre = root; // pre指针初始 } else { if (pre.val > root.val) { if (first == null) { first = pre;// 第一个逆序点,incorrect smaller node is always found // as prev node } second = root; // 不断寻找最后一个逆序点,incorrect larger node is always // found as curr(root) node } pre = root; // pre指针每次后移一位 } inorder(root.right); } public static void recoverTree(TreeNode root) { pre = null; first = null; second = null; inorder(root); if (first != null && second != null) { int tmp = first.val; first.val = second.val; second.val = tmp; } } /* * 自己的代码,用的stack来做 */ public static void recoverTree1(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; TreeNode pre = null; TreeNode first = null; TreeNode second = null; while (!stack.isEmpty() || cur != null) { if (cur != null) { stack.push(cur); cur = cur.left; } else { TreeNode p = stack.pop(); // 这里出现的p就是inorder里面不断出现的最小的数,就是最左边的数 if (pre != null && p.val <= pre.val) { if (first == null) { first = pre; } second = p; } pre = p; cur = p.right; } } if (first != null && second != null) { int tmp = first.val; first.val = second.val; second.val = tmp; } }