99. Recover Binary Search Tree

来源:互联网 发布:淘宝充值平台关闭了 编辑:程序博客网 时间:2024/06/05 11:13

做这题的时候发现其实上一题的做法是错误的,BST的中序排序是一个上升序列,所以判断的时候只需要按中序排序, 然后判断是不是上升的就ok!所以98也是这样做的!!!
至于这题,为什么n1 和 n2 记录的不一样呢? N1 是记录pre的而n2是记录root的
因为你在纸上写一个上升序列,然后换砖两个数,你就会发现原因!!!

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int num;    TreeNode* n1;    TreeNode* n2;    TreeNode* pre = new TreeNode(INT_MIN);    //int pre;    void change(TreeNode* root){        if(root == NULL) return ;        change(root -> left);        if(num == 0 && pre -> val >= root -> val){            num ++;            n1 = pre;        }        if(num != 0 && pre -> val >= root -> val)            n2 = root;        pre = root;        change(root -> right);    }    void recoverTree(TreeNode* root) {        if(root == NULL) return ;        num = 0;        change(root);        int t;        t = n1 -> val; n1 -> val = n2 -> val; n2 -> val = t;    }};
0 0
原创粉丝点击