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.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private TreeNode pre; private TreeNode first; private TreeNode second; public void inorder(TreeNode root){ if (root == null) { return; } inorder(root.left); if (pre == null) { pre = root; } else { if (pre.val >= root.val) { if (first == null) { first = pre; } second = root; } pre = root; } inorder(root.right); } public void recoverTree(TreeNode root) { inorder(root); if (first!=null && second!=null) { int tmp = first.val; first.val = second.val; second.val = tmp; } } }
相关推荐
java java_leetcode-99-recover-binary-search-tree
python python_leetcode题解之099_Recover_Binary_Search_Tree
js js_leetcode题解之99-recover-binary-search-tree.js
c语言基础 c语言_leetcode题解之0099_recover_binary_search_tree.zip
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
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)。这道题要求恢复一棵二叉搜索树中两个节点的值,使得树重新符合二叉搜索树的性质。二叉搜索树的特点是左子树上的所有节点值小于父节点...
* [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]...
- BinaryTree(二叉树) - HuffmanCompression(霍夫曼编码) - Queue(队列) - Heap(堆) - Stack(栈) - Set(集合) - Map(映射/哈希表) - Graph(图) - **Basics Sorting**(基本排序算法) - ...
- **二叉树(Binary Tree)** - 二叉树是一种树形结构,其中每个节点最多有两个子节点。 - 常见类型包括平衡二叉树、二叉搜索树等。 - **哈夫曼编码(Huffman Compression)** - 是一种基于频率的压缩技术,广泛应用...