LeetCode_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.
Solution and Precautions:
The basic idea is to in-order traverse the whole tree and find the reversed pair and fix them. The following are based on the same in-order traverse but using different space.
(1) using average O(N) space. use perform regular in-order traverse on the whole tree and store all the node pointers in an allocated vector or array, find the reversed pair in the array, and swap the values pointed by the stored pointers. The allocated array cost O(N) space averagely
(2) average O(log N) space but O(N) in worst case. Still do in-order traverse but without the the allocated array in (1), this could be down by keeping two pointers prev and current which point to the consecutive nodes in the in-order sequence, during one pass in-order traverse, we keep comparing them (pre->val, current->val) and we can get the first and second pointers to the swapped wrong nodes. After finishing the in-order traverse, you swap back the two wrong nodes. And we are down. Since we do recursive in-order traverse, we still allocate additional memory in the stack which is O(hight of the tree), so the space we use is actually average O(log N) space but O(N) in worst case.
(3) real constant space. In order to get constant space, we have to be able to do the in-order traverse without using the stack, then we might need to get the help of the “threaded binary tree”. By following the threaded binary tree, we make use of the NULL node of the leaf node by making the right NULL child of the leaf node point to the next node in the in-order sequence, we are able to do the in-order traverse without using stack and thus constant memory, combing (2) we only need another two pointers Prev, Curret, to keep traversing the while tree in in-order and another two Ptr1, Ptr2 to keep record of the reversed nodes. Then then finish swapping them. And all these are be achieved by using constant number of pointers. This is constant space solution.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void inOrder(TreeNode *root){
if(root->left ) inOrder(root->left);
if(pre == NULL) pre = root;
else if(pre-> val > root->val ){
if(first == NULL)
first = pre;
second = root;
}
pre = root;
if(root->right ) inOrder(root->right);
}
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL) return;
first = NULL;
second = NULL;
pre = NULL ;
inOrder(root);
int temp = first->val ;
first->val = second->val;
second->val = temp;
}
private :
TreeNode * first;
TreeNode * second;
TreeNode * pre;
};
reference :http://tech-wonderland.net/blog/leetcode-recover-binary-search-tree.html#comment-2742
LeetCode_Recover Binary Search Tree的更多相关文章
- [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法
二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...
- Leetcode 笔记 99 - Recover Binary Search Tree
题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...
- Leetcode 笔记 98 - Validate Binary Search Tree
题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...
- Leetcode: Convert sorted list to binary search tree (No. 109)
Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...
- [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- [LeetCode] Closest Binary Search Tree Value 最近的二分搜索树的值
Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...
- [LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...
- [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
随机推荐
- LeetCode_Scramble String
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrin ...
- BZOJ1211: [HNOI2004]树的计数
1211: [HNOI2004]树的计数 Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1245 Solved: 383[Submit][Statu ...
- zoj3640:概率(期望)dp
题目大意:有一个吸血鬼,初始攻击力为f,每天随机走到n个洞里面,每个洞有一个c[i],如果他的攻击力f>c[i] 则可以花费t[i] 的时间逃走,否则则花费一天时间使自己的攻击力增加c[i],求 ...
- shiro内置过滤器研究
anon org.apache.shiro.web.filter.authc.AnonymousFilter authc org.apache.shiro.web.filter.authc.FormA ...
- 修改过mysql数据库字段内容默认值为当前时间
--添加CreateTime 设置默认时间 CURRENT_TIMESTAMP ALTER TABLE `table_name`ADD COLUMN `CreateTime` datetime N ...
- python wmi模块学习
# -*- coding: cp936 -*- import wmi c = wmi.WMI () for sys in c.Win32_OperatingSystem(): print " ...
- 分享一个option样式传递给select当前选中样式
今天遇到一个很是纠结的问题,需求又改了!原生的select给option加样式,结果发现select选中仍是默认样式,如下图:
- 奔五的人学IOS:swift练手与csdn,最近学习总结
早在五月份就准备開始学习ios开发,当时还是oc,学习了几天,最终不得其法.到了ios8开放,再加swift的出现.从10月份開始.最终找到了一些技巧,学习起来还算略有心得. 今天把我在学习swift ...
- LDAP禁止匿名访问
LDAP默认是允许用户匿名访问的,如下图:在使用工具连接时,勾选匿名绑定后,不需要输入UserDN和密码就可能连接到LDAP服务器,但是只能进行read及search操作.不能做任何的修改及删除操作. ...
- DEV GridControl 根据单元格值改变背景色
GridControl 根据单元格值改变背景色(需要用到CustomDrawCell事件) 方法1: private void gdvClient_CustomDrawCell(object send ...