LeetCode 99. Recover Binary Search Tree
来源:互联网 发布:linux 挂载u盘 wrong 编辑:程序博客网 时间:2024/06/05 18:19
题目
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?
题解
最简单的办法,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作。
但这种方法要求n的空间复杂度,题目中要求空间复杂度为常数,所以需要换一种方法。
递归中序遍历二叉树,设置一个pre指针,记录当前节点中序遍历时的前节点,如果当前节点大于pre节点的值,说明需要调整次序。
代码
class Solution {public: TreeNode *mis1, *mis2; TreeNode *pre; void gao( TreeNode *root ){ if( root == NULL ) return; if( root->left != NULL ){ gao( root->left ); } if( pre != NULL && root->val < pre->val ){ if( mis1 == NULL ){ mis1 = pre; mis2 = root; }else{ mis2 = root; } } pre = root; if( root->right != NULL ){ gao( root->right ); } } void recoverTree(TreeNode* root) { mis1 = mis2 = NULL; pre = NULL; gao( root ); if( mis1 != NULL && mis2 != NULL ){ int tmp = mis1->val; mis1->val = mis2->val; mis2->val = tmp; } }};
0 0
- LeetCode 99. Recover Binary Search Tree
- [LeetCode]99.Recover Binary Search Tree
- [Leetcode] 99. Recover Binary Search Tree
- LeetCode --- 99. Recover Binary Search Tree
- [leetcode] 99.Recover Binary Search Tree
- leetcode 99. Recover Binary Search Tree
- Leetcode 99. Recover Binary Search Tree
- LeetCode 99. Recover Binary Search Tree
- LeetCode 99. Recover Binary Search Tree
- Leetcode 99. Recover Binary Search Tree
- LeetCode 99. Recover Binary Search Tree
- [LeetCode] 99. Recover Binary Search Tree
- leetcode-99. Recover Binary Search Tree
- LeetCode 99. Recover Binary Search Tree
- [LeetCode] 99. Recover Binary Search Tree
- leetcode 99. Recover Binary Search Tree
- leetcode 99. Recover Binary Search Tree
- [leetcode]99. Recover Binary Search Tree
- 飞得更高(一)陌生电话
- librtmp协议分析---RTMP_ConnectStream函数
- P1071 潜伏者
- composer在xdebug开启的情况下会有一个warning
- 从AppStore上下载的程序在iOS9.2.1系统下一启动就秒退
- LeetCode 99. Recover Binary Search Tree
- 软件测试发展现状及未来
- <<深入理解Flask>>中遇到的那些坑
- 偶然发现mysql的表中字段居然不区分大小写
- git常用操作
- Android中一个app启动另一个app的指定activity
- Git入门——本地版本库操作
- docker脚本安装
- ssh免密登录设置