您的位置:首页 > 其它

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: