Recover Binary Search Tree
2013-09-09 08:24
169 查看
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void Inorder(TreeNode *root, vector<TreeNode*> &nodes, vector<int> &vals) { if (!root) return; Inorder(root->left, nodes, vals); nodes.push_back(root); vals.push_back(root->val); Inorder(root->right, nodes, vals); } //void sort(vector<int> &vals) void recoverTree(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<TreeNode*> nodes; vector<int> vals; Inorder(root, nodes, vals); sort(vals.begin(), vals.end()); for (int i=0; i<nodes.size(); i++) { nodes[i]->val=vals[i]; } } };
Use inorder traverse because the numbers will be stored in an ascending order. The above solution need array to store all the values and consume O(n) space.
Below is the method needing O(1) space.
class Solution {
public:
TreeNode *n1, *n2, *pre;
void inOrder(TreeNode *root) {
if (!root) return;
inOrder(root->left);
if (pre && pre->val > root->val) {
if (!n1) n1=pre;
n2=root;
}
pre=root;
inOrder(root->right);
}
void recoverTree(TreeNode *root) {
n1=NULL; n2=NULL; pre=NULL;
inOrder(root);
int temp=n1->val;
n1->val=n2->val;
n2->val=temp;
}
};
相关文章推荐
- [LeetCode] Recover Binary Search Tree
- LeetCode | Recover Binary Search Tree
- Recover Binary Search Tree
- leetcode99 Recover Binary Search Tree java 算法
- Recover Binary Search Tree -- LeetCode
- ***(leetcode) Recover Binary Search Tree
- LeetCode-Recover Binary Search Tree
- Recover Binary Search Tree
- leetCode_Recover Binary Search Tree
- leetcode Recover Binary Search Tree
- LeetCode Recover Binary Search Tree
- 【LeetCode #99】Recover Binary Search Tree
- [leetcode 99] Recover Binary Search Tree
- Recover Binary Search Tree
- LeetCode--Recover Binary Search Tree
- [LeetCode]Recover Binary Search Tree
- Recover Binary Search Tree (Java)
- [leetcode]Recover Binary Search Tree
- LeetCode算法题目:Recover Binary Search Tree
- Leetcode: Recover Binary Search Tree