LeetCode: Recover Binary Search Tree
2012-12-06 03:57
393 查看
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?
Space O(n)的方法就是自己用stack来模拟inorder traverse ,然后将输出的结果存在一个vector里面,然后遍历vector找到冲突的对。
Space constant的方法就是用递归的方式进行inorder traverse,然后在遍历的过程中记录一个前驱节点,然后比较前驱节点和当前节点的值,将结果记录下来,最后交换一下就行了。
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?
Space O(n)的方法就是自己用stack来模拟inorder traverse ,然后将输出的结果存在一个vector里面,然后遍历vector找到冲突的对。
Space constant的方法就是用递归的方式进行inorder traverse,然后在遍历的过程中记录一个前驱节点,然后比较前驱节点和当前节点的值,将结果记录下来,最后交换一下就行了。
class Solution { public: TreeNode * inorderVisit(TreeNode *root, TreeNode *pre, vector<TreeNode *> &res){ if(root == NULL){return pre;} TreeNode *last; last = inorderVisit(root->left, pre, res); if(last == NULL){ last = root; } if(root->val < last->val){ if(res[0] == NULL){ res[0] = last; res[1] = root; } else{ res[1] = root; } } last = inorderVisit(root->right, root, res); return last == NULL? root : last; } void recoverTree(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return; vector<TreeNode *> res(2); TreeNode *last = inorderVisit(root, NULL, res); swap(res[0]->val, res[1]->val); return; } };
相关文章推荐
- leetcode~Recover Binary Search Tree
- leetcode hard模式专杀之99. Recover Binary Search Tree
- leetcode---recover-binary-search-tree---树
- [leetcode-99]Recover Binary Search Tree(java)
- leetcode 124: Recover Binary Search Tree
- Leetcode Recover Binary Search Tree
- LeetCode Recover Binary Search Tree
- LeetCode99—Recover Binary Search Tree
- [leetcode] #25 Recover Binary Search Tree
- Recover Binary Search Tree -- LeetCode
- [LeetCode]Recover Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- [LeetCode]Recover Binary Search Tree
- 二叉树系列 - 二叉搜索树 - [LeetCode] 中序遍历中利用 pre节点避免额外空间。题:Recover Binary Search Tree,Validate Binary Search Tree
- leetcode-Recover Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- leetcode_c++:树: Recover Binary Search Tree(099)
- [LeetCode] - Recover Binary Search Tree
- [LeetCode]Recover Binary Search Tree
- LeetCode---Recover Binary Search Tree