新博文地址:[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?
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?
这道题想复杂了,上午花了一个多小时都没弄出来,晚上换了一种思路,不到半小时就AC了,总的来说,判断是不是BST还是中序遍历最方便,但是题中说道O(n)复杂度太easy,要求开常量空间。
具体的思路,还是通过中序遍历,只不过,不需要存储每个节点,只需要存一个前驱即可。
例如1,4,3,2,5,6
1.当我们读到4的时候,发现是正序的,不做处理
2.但是遇到3时,发现逆序,将4存为第一个错误节点,3存为第二个错误节点
3.继续往后,发现3,2又是逆序了,那么将第2个错误节点更新为2
如果是这样的序列:1,4,3,5,6同上,得到逆序的两个节点为4和3。
同理对于边界情况也是可以处理的,例如2,1
TreeNode first = null,second = null,pre = null; public void recoverTree(TreeNode root) { findNode(root); swap(first, second); } private void findNode(TreeNode root){ if(root == null){ return; } if(root.left != null ) findNode(root.left); if(pre != null && root.val < pre.val){ if(first == null){ first = pre; } second = root; } pre = root; if(root.right != null) findNode(root.right); } private void swap(TreeNode node1,TreeNode node2){ int tem = node1.val; node1.val = node2.val; node2.val = tem; }
以上
相关推荐
java java_leetcode-99-recover-binary-search-tree
python python_leetcode题解之099_Recover_Binary_Search_Tree
c语言基础 c语言_leetcode题解之0099_recover_binary_search_tree.zip
js js_leetcode题解之99-recover-binary-search-tree.js
lru缓存leetcode leetcode 大批 41. First Missing Positive 广度优先搜索 ...Recover Binary Search Tree 109. Convert Sorted List to Binary Search Tree 116. Populating Next Right Pointers in Each No
* [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search]...
Recover Binary Search Tree - Java Recursive 0101 Symmetric tree - Java Recursive - Java Iterative - C Recursive - Python Iterative 0102 Binary Tree Level Order Traversal - Python3 iterative 0103...
- **Recover Binary Search Tree**:恢复二叉搜索树中的两个错误节点。 - **Binary Tree Path**:找到二叉树中和为目标值的路径。 - **Sum Root to Leaf Numbers**:计算二叉树所有从根到叶子节点的路径之和。 4...
本篇内容将深入解析Python在LeetCode面试中的第99题——恢复二叉搜索树(Recover Binary Search Tree)。 二叉搜索树(Binary Search Tree,BST)是一种特殊的二叉树,它的每个节点都满足以下性质:左子树上所有...
接着,我们来看第9题,"恢复二叉搜索树的顺序"( Recover Binary Search Tree)。这道题要求恢复一棵二叉搜索树中两个节点的值,使得树重新符合二叉搜索树的性质。二叉搜索树的特点是左子树上的所有节点值小于父节点...
- BinaryTree(二叉树) - HuffmanCompression(霍夫曼编码) - Queue(队列) - Heap(堆) - Stack(栈) - Set(集合) - Map(映射/哈希表) - Graph(图) - **Basics Sorting**(基本排序算法) - ...
Recover a Tree From Preorder Traversal Hard (73.62 %) [1027] Longest Arithmetic Sequence Medium (41.26 %) [1026] Maximum Difference Between Node and Ancestor Medium (55.48 %) [1025] Divisor Game Easy ...