leetcode — recover-binary-search-tree
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Source : https://oj.leetcode.com/problems/recover-binary-search-tree/
*
*
* Two elements of a binary search tree (BST) are swapped by mistake.
*
* Recover the tree without changing its structure.
*
* Note:
* A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
*
* confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
*
* OJ's Binary Tree Serialization:
*
* The serialization of a binary tree follows a level order traversal, where '#' signifies
* a path terminator where no node exists below.
*
* Here's an example:
*
* 1
* / \
* 2 3
* /
* 4
* \
* 5
*
* The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*/
public class RecoverBinarySearchTree {
private TreeNode n1;
private TreeNode n2;
private TreeNode pre;
/**
* 搜索二叉树
* 将错误调换位置的两个元素恢复位置
*
* 先中序遍历树,将节点的value放到一个数组中,并将节点也放到一个数组中
* 然后将value数组排序
* 然后依次赋值给节点数组中每个节点,然后将节点数组恢复成一棵树
* 占用空间为O(n)
*
* @param root
* @return
*/
public TreeNode recover (TreeNode root) {
List<Integer> arr = new ArrayList<Integer>();
List<TreeNode> treeList = new ArrayList<TreeNode>();
traverseInorder(root, arr, treeList);
Collections.sort(arr);
for (int i = 0; i < arr.size(); i++) {
treeList.get(i).value = arr.get(i);
}
return root;
}
public void traverseInorder (TreeNode root, List<Integer> arr, List<TreeNode> treeList) {
if (root == null) {
return ;
}
traverseInorder(root.leftChild, arr, treeList);
arr.add(root.value);
treeList.add(root);
traverseInorder(root.rightChild, arr, treeList);
}
/**
* 二叉搜索树:中序遍历的时候是单调递增的
*
* 中序遍历树,将树遍历为一个链表,当前节点的值一定大于上一个节点的值,否则就是被调换的节点,中序遍历的时候记录调换的两个节点
* 因为只有两个节点被置换,所以如果是第一次出现上一个节点的值大于当前节点,说明是被换到其前面的节点,所以被置换的是上一个节点
* 如果是第二次出现上一个节点的值大于当前节点,那么当前节点是被置换的节点
* 中序遍历完成后,调换记录的两个节点的值,就恢复了二叉搜索树
*
* @param root
* @return
*/
public TreeNode recoverTree (TreeNode root) {
traverseInorder(root);
if (n1 != null && n2 != null) {
int temp = n1.value;
n1.value = n2.value;
n2.value = temp;
}
return root;
}
public void traverseInorder (TreeNode root) {
if (root == null) {
return;
}
traverseInorder(root.leftChild);
if (pre != null) {
if (pre.value > root.value) {
if (n1 == null) {
n1 = pre;
}
n2 = root;
}
}
pre = root;
traverseInorder(root.rightChild);
}
public TreeNode createTree (char[] treeArr) {
TreeNode[] tree = new TreeNode[treeArr.length];
for (int i = 0; i < treeArr.length; i++) {
if (treeArr[i] == '#') {
tree[i] = null;
continue;
}
tree[i] = new TreeNode(treeArr[i]-'0');
}
int pos = 0;
for (int i = 0; i < treeArr.length && pos < treeArr.length-1; i++) {
if (tree[i] != null) {
tree[i].leftChild = tree[++pos];
if (pos < treeArr.length-1) {
tree[i].rightChild = tree[++pos];
}
}
}
return tree[0];
}
/**
* 使用广度优先遍历将树转化为数组
*
* @param root
* @param chs
*/
public void binarySearchTreeToArray (TreeNode root, List<Character> chs) {
if (root == null) {
chs.add('#');
return;
}
List<TreeNode> list = new ArrayList<TreeNode>();
int head = 0;
int tail = 0;
list.add(root);
chs.add((char) (root.value + '0'));
tail ++;
TreeNode temp = null;
while (head < tail) {
temp = list.get(head);
if (temp.leftChild != null) {
list.add(temp.leftChild);
chs.add((char) (temp.leftChild.value + '0'));
tail ++;
} else {
chs.add('#');
}
if (temp.rightChild != null) {
list.add(temp.rightChild);
chs.add((char)(temp.rightChild.value + '0'));
tail ++;
} else {
chs.add('#');
}
head ++;
}
//去除最后不必要的
for (int i = chs.size()-1; i > 0; i--) {
if (chs.get(i) != '#') {
break;
}
chs.remove(i);
}
}
private class TreeNode {
TreeNode leftChild;
TreeNode rightChild;
int value;
public TreeNode(int value) {
this.value = value;
}
public TreeNode() {
}
}
public static void main(String[] args) {
RecoverBinarySearchTree recoverBinarySearchTree = new RecoverBinarySearchTree();
char[] tree = new char[]{'3','4','5','#','#','2'};
List<Character> chars = new ArrayList<Character>();
recoverBinarySearchTree.binarySearchTreeToArray(recoverBinarySearchTree.recover(recoverBinarySearchTree.createTree(tree)), chars);
System.out.println(Arrays.toString(chars.toArray(new Character[chars.size()])));
chars = new ArrayList<Character>();
recoverBinarySearchTree.binarySearchTreeToArray(recoverBinarySearchTree.recoverTree(recoverBinarySearchTree.createTree(tree)), chars);
System.out.println(Arrays.toString(chars.toArray(new Character[chars.size()])));
}
}
leetcode — recover-binary-search-tree的更多相关文章
- LeetCode: Recover Binary Search Tree 解题报告
Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recove ...
- [LeetCode] Recover Binary Search Tree 复原二叉搜索树
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...
- [leetcode]Recover Binary Search Tree @ Python
原题地址:https://oj.leetcode.com/problems/recover-binary-search-tree/ 题意: Two elements of a binary searc ...
- [Leetcode] Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...
- LeetCode: Recover Binary Search Tree [099]
[题目] Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without cha ...
- [Leetcode] Recover binary search tree 恢复二叉搜索树
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...
- LeetCode Recover Binary Search Tree——二查搜索树中两个节点错误
Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing ...
- [线索二叉树] [LeetCode] 不需要栈或者别的辅助空间,完成二叉树的中序遍历。题:Recover Binary Search Tree,Binary Tree Inorder Traversal
既上篇关于二叉搜索树的文章后,这篇文章介绍一种针对二叉树的新的中序遍历方式,它的特点是不需要递归或者使用栈,而是纯粹使用循环的方式,完成中序遍历. 线索二叉树介绍 首先我们引入“线索二叉树”的概念: ...
- Leetcode 笔记 99 - Recover Binary Search Tree
题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...
- [LeetCode] 99. Recover Binary Search Tree(复原BST) ☆☆☆☆☆
Recover Binary Search Tree leetcode java https://leetcode.com/problems/recover-binary-search-tree/di ...
随机推荐
- 数据库SQLServr安装时出现--"需要更新以前的Visual Studio 2010实例"--状态失败
在电脑中安装过Visual Studio比较低版本的软件的时候 将原本的Microsoft Visual Studio 2010 Service Pack 1进行了更改 导致sql比较高版本的不能很好 ...
- 大数据计算框架Hadoop, Spark和MPI
转自:https://www.cnblogs.com/reed/p/7730338.html 今天做题,其中一道是 请简要描述一下Hadoop, Spark, MPI三种计算框架的特点以及分别适用于什 ...
- nodejs操作mysql常见错误
1.Cannot enqueue Handshake after already enqueuing a Hand shake.这个错误提示意思是某个数据库连接已经执行了,不能进行多次连接了.遇到此类 ...
- async ,await 有图有真相
1.async返回的一定是promise对象 2.await确实可以同步:
- COCOMOII的使用说明
if(airline.equals("欧美")) { result="所有座位都有食物供应,每个座位都可以播放电影"; } if(airline.equals( ...
- .NET 应用架构电子书中文版
<.NET 微服务:容器化 .NET 应用架构指南> 本书主要介绍了基于容器和微服务的应用架构和设计原则,以及基于 .NET Core 和 Docker 容器的应用程序开发实践.为了让大家 ...
- app性能测试,你需要关注哪些指标?
app性能测试,你需要关注哪些指标? 一.Android客户端性能测试常见指标: 1.内存 2.CPU 3.流量 4.电量 5.启动速度 6.滑动速度.界面切换速度 7.与服务器交互的网络速度 二.预 ...
- 仿微信的IM聊天时间显示格式(含iOS/Android/Web实现)[图文+源码]
本文为原创分享,转载请注明出处. 1.引言 即时通讯IM应用中的聊天消息时间显示是个再常见不过的需求,现在都讲究用户体验,所以时间显示再也不能像传统软件一样简单粗地暴显示成“年/月/日 时:分:秒”这 ...
- [Swift]LeetCode307. 区域和检索 - 数组可修改 | Range Sum Query - Mutable
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- [Swift]LeetCode375. 猜数字大小 II | Guess Number Higher or Lower II
We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to gues ...