Recover Binary Search Tree Solutions in Java
Number 99
Difficulty Hard
Acceptance 39.8%
Link LeetCode
Solutions
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/validate-binary-search-tree/description//// Author : liuyubobobo/// Time : 2018-05-22import java.util.ArrayList;/// Using inOrder traverse/// Store all Nodes in an ArrayList and find the mistaked swapped nodes////// Time Complexity: O(n)/// Space Complexity: O(n)class Solution {public void recoverTree(TreeNode root) {ArrayList<TreeNode> list = new ArrayList<>();inOrder(root, list);TreeNode a = null;TreeNode b = null;for(int i = 1 ; i < list.size() ; i ++) {if (list.get(i - 1).val > list.get(i).val) {if (a == null){a = list.get(i - 1);b = list.get(i);}else {b = list.get(i);break;}}}int t = a.val;a.val = b.val;b.val = t;}private void inOrder(TreeNode node, ArrayList<TreeNode> list){if(node == null)return;inOrder(node.left, list);list.add(node);inOrder(node.right, list);}public static void main(String[] args){TreeNode root = new TreeNode(3);root.left = new TreeNode(1);root.right = new TreeNode(4);root.right.left = new TreeNode(2);(new Solution()).recoverTree(root);}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/validate-binary-search-tree/description//// Author : liuyubobobo/// Time : 2018-05-22/// Using inOrder traverse/// Find the mistaked swapped nodes during the traversing////// Time Complexity: O(n)/// Space Complexity: O(h)class Solution2 {private TreeNode pre;private TreeNode a, b;public void recoverTree(TreeNode root) {pre = null;a = null;b = null;inOrder(root);int t = a.val;a.val = b.val;b.val = t;}private void inOrder(TreeNode node){if(node == null)return;inOrder(node.left);if(pre != null && pre.val > node.val){if (a == null){a = pre;b = node;}elseb = node;}pre = node;inOrder(node.right);}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/validate-binary-search-tree/description//// Author : liuyubobobo/// Time : 2018-05-29/// Using Morris inOrder traversal/// Find the mistaked swapped nodes during the traversing////// Time Complexity: O(n)/// Space Complexity: O(1)class Solution3 {private TreeNode pre;private TreeNode a, b;public void recoverTree(TreeNode root) {TreeNode cur = root;while(cur != null){if(cur.left == null){process(cur);cur = cur.right;}else{TreeNode prev = cur.left;while(prev.right != null && prev.right != cur)prev = prev.right;if(prev.right == null){prev.right = cur;cur = cur.left;}else{prev.right = null;process(cur);cur = cur.right;}}}int t = a.val;a.val = b.val;b.val = t;}private void process(TreeNode node){if(pre != null && pre.val > node.val){if(a == null){a = pre;b = node;}elseb = node;}pre = node;}}