[leetCode] Recover Binary Search Tree
LeetCode Tree search Binary recover
2023-09-11 14:17:25 时间
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.
Tree Depth-first Search
思路:
O(n) 空间的解法是,开一个指针数组,中序遍历,将节点指针依次存放到数组里,然后寻找两
处逆向的位置,先从前往后找第一个逆序的位置,然后从后往前找第二个逆序的位置,交换这两个
指针的值。
中序遍历一般需要用到栈,空间也是 O(n) 的,如何才能不使用栈?Morris 中序遍历。
方法一:中序遍历
class Solution { public: void recoverTree(TreeNode *root) { vector<TreeNode*> result; stack<TreeNode*> st; TreeNode* p = root; // inorder traverse while(p != NULL || st.size() != 0) { while(p != NULL) { st.push(p); p = p->left; } if(!st.empty()) { p = st.top(); st.pop(); result.push_back(p); p = p->right; } } TreeNode* r1 = NULL, *r2 = NULL; for(int i = 0; i < result.size()-1; i++) { if(result[i]->val > result[i+1]->val) { r1 = result[i]; break; } } for(int i = result.size()-1; i >= 1; i--) { if(result[i]->val < result[i-1]->val) { r2 = result[i]; break; } } //swap r1 and r2's value int tmp = r1->val; r1->val = r2->val; r2->val = tmp; } };
相关文章
- Leetcode: Verify Preorder Sequence in Binary Search Tree
- Leetcode: Binary Search Tree Iterator
- Leetcode: Convert Sorted List to Binary Search Tree
- BZOJ 2631 tree 动态树(Link-Cut-Tree)
- [LeetCode] Balanced Binary Tree
- [LeetCode] Convert Sorted Array to Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- 【LeetCode】99. Recover Binary Search Tree
- 【LeetCode】103. Binary Tree Zigzag Level Order Traversal
- [LeetCode] Convert Sorted Array to Binary Search Tree
- [LeetCode] 971. Flip Binary Tree To Match Preorder Traversal 翻转二叉树以匹配先序遍历
- [LeetCode] 919. Complete Binary Tree Inserter 完全二叉树插入器
- [LeetCode] 834. Sum of Distances in Tree 树中距离之和
- [LeetCode] 889. Construct Binary Tree from Preorder and Postorder Traversal 由先序和后序遍历建立二叉树
- [LeetCode] Trim a Binary Search Tree 修剪一棵二叉搜索树
- [LeetCode] Find Mode in Binary Search Tree 找二分搜索数的众数
- [LeetCode] 266. Palindrome Permutation 回文全排列
- [LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)
- [LeetCode] 98. Validate Binary Search Tree 验证二叉搜索树
- [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树
- [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器
- [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先(简单)