LeetCode 99: Recover Binary Search Tree
2013-09-08 21:13
615 查看
Difficulty: 4
Frequency: 2
Problem:
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?
Solution:
Notes:
Lots of subtleties.
Frequency: 2
Problem:
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?
Solution:
class Solution { public: void recoverTree(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function TreeNode *p_last, *p_small, *p_big; bool b_big = true; p_small = p_big = NULL; int i_last = INT_MIN; Traverse(root, i_last, p_last, p_small, p_big, b_big); i_last = p_small->val; p_small->val = p_big->val; p_big->val = i_last; } void Traverse(TreeNode * root, int & i_last, TreeNode * & p_last, TreeNode *& p_small, TreeNode *& p_big, bool & b_big) { if (root==NULL) return; if (root->left) Traverse(root->left, i_last, p_last, p_small, p_big, b_big); if (i_last>root->val) { if (b_big) { p_big = p_last; b_big = !b_big; p_small = root;// Doing this is because the swapped two may be adjacent. } else { p_small = root; return; } } i_last = root->val; p_last = root; if (root->right) Traverse(root->right, i_last, p_last, p_small, p_big, b_big); } };
Notes:
Lots of subtleties.
相关文章推荐
- LeetCode(99) Recover Binary Search Tree
- leetcode || 99、Recover Binary Search Tree
- LeetCode99 Recover Binary Search Tree
- leetcode hard模式专杀之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
- leetcode99---Recover Binary Search Tree(morris中序遍历恢复BST)
- LeetCode 99 Recover Binary Search Tree(Python详解及实现)
- LeetCode力扣之99. Recover Binary Search Tree
- leetcode[99]Recover Binary Search Tree
- Leetcode 99 Recover Binary Search Tree
- LeetCode99—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
- leetcode99 Recover Binary Search Tree java 算法
- [leetcode]99 Recover Binary Search Tree