Recover Binary Search Tree

来源:互联网 发布:失踪的宝贝知乎 编辑:程序博客网 时间:2024/05/17 07:48
/** * 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;    }};


原创粉丝点击