4.6 leetcode -6 recover-binary-search-tree

来源:互联网 发布:各省人口普查数据 编辑:程序博客网 时间:2024/06/05 10:54
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"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5

The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".


这题,中序遍历是关键,因为中序遍历的结果应该是从小到大。

然后分情况,假如整个就一组颠倒,例如124356,那么直接交换43和就行。假如有2组比如163452。则需要把第一组63的6和52的2作交换。

代码:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int errnum = 0;    TreeNode* errNode1;    TreeNode* errNode2;    TreeNode* errNode3;    TreeNode* errNode4;    TreeNode* tmp;    int number = -1000;    int cnt = 0;    void recoverTree(TreeNode *root) {        cnt ++;        if(root == NULL)        {            cnt --;            return;        }        else            {            recoverTree(root->left);            if(root->val > number)                {                tmp = root;                number = root->val;            }            else                {                number = root->val;                if(errnum == 0)                    {                    errNode1 = tmp;                    errNode2 = root;                    errnum++;                }                else                    {                    errNode3 = tmp;                    errNode4 = root;                    errnum ++;                                        int tmp1 = root->val;                    root->val = errNode1->val;                    errNode1->val = tmp1;                }            }            recoverTree(root->right);        }        cnt --;        if(cnt == 0 && errnum == 1)            {            int tmp1 = errNode1->val;            errNode1->val = errNode2->val;            errNode2->val = tmp1;        }    }};

潜在bug,按道理第一个数是怎么都要存的,我为了让他存,随便给了个-1000,这里操作有问题,假如最小数小于-1000就尬了

原创粉丝点击