[leetcode] Recover Binary Search Tree
2013-08-19 15:49
417 查看
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
read more on how binary tree is serialized on OJ.
二叉树中有两个节点swap了一下,现在需要你去纠正,题目中有个o(n)的算法,初步想法是可以对其进行先序遍历,然后将节点存储到一个数组中去,再遍历这个数组,找到两个反序了的数,将他们的值交换一下。
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.
二叉树中有两个节点swap了一下,现在需要你去纠正,题目中有个o(n)的算法,初步想法是可以对其进行先序遍历,然后将节点存储到一个数组中去,再遍历这个数组,找到两个反序了的数,将他们的值交换一下。
class Solution { public: void recoverTree(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function TreeNode **array=new TreeNode*[1000]; int count=0; int p,q; p=0,q=0; putintoarray(root,array,count); for(int i=1 ; i<count ; i++){ if(array[i-1]->val>array[i]->val) swap(array[i-1]->val,array[i]->val); } for(int i=count-2 ; i>=0 ; i--){ if(array[i]->val>array[i+1]->val) swap(array[i]->val,array[i+1]->val); } delete array; } void swap(int& a , int & b){ if(a==b) return; a=a^b; b=a^b; a=a^b; } void putintoarray(TreeNode *root , TreeNode **p, int& i){ if(!root) return; if(root->left) putintoarray(root->left,p,i); p[i++]=root; if(root->right) putintoarray(root->right,p,i); } };
相关文章推荐
- [Leetcode] Validate Binary Search Tree & Recover Binary Search Tree
- leetcode -day27 Recover Binary Search Tree & Interleaving String
- LeetCode-Recover Binary Search Tree-恢复二叉排序树
- [leetcode] Recover Binary Search Tree
- [leetcode] recover binary search tree
- LeetCode: Recover Binary Search Tree
- [leetcode] Recover Binary Search Tree
- leetcode--Recover Binary Search Tree
- 101_leetcode_Recover Binary Search Tree
- [leetCode] Recover Binary Search Tree
- LeetCode 99: Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- [leetcode] Recover Binary Search Tree
- LeetCode 99 Recover Binary Search Tree
- LeetCode Recover Binary Search Tree
- LeetCode 53 Recover Binary Search Tree
- Leetcode 笔记 99 - Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- [leetcode刷题系列]Recover Binary Search Tree