【LeetCode 99】Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

 

题意:

  一颗二叉搜索树中有2个结点的元素被误换了,要求恢复二叉搜索树的原状。

思路:

  中序遍历BST,若发现一次逆序,说明是两个相连结点的误换,直接交换结点的值;若发现两次逆序,则为不相连的两个结点误换,交换错误的结点即可。用一个变量保存先前结点的状态,若发生逆序则记录,空间复杂度为常量。

 

C++:

 1 /**

 2  * Definition for a binary tree node.

 3  * struct TreeNode {

 4  *     int val;

 5  *     TreeNode *left;

 6  *     TreeNode *right;

 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 8  * };

 9  */

10 class Solution {

11 public:

12 

13     vector<TreeNode* > errs;

14     TreeNode *preNode;

15     

16     void rec(TreeNode *root)

17     {

18         if(root->left != 0)

19             rec(root->left);

20         

21         if(preNode != 0 && root->val < preNode->val)

22         {

23             errs.push_back(preNode);

24             errs.push_back(root);

25         }

26         

27         preNode = root;

28         

29         if(root->right != 0)

30             rec(root->right);

31     }

32     

33     void recoverTree(TreeNode* root) {

34         if(root == 0)

35             return ;

36         

37         preNode = 0;

38         

39         rec(root);

40         

41         int temp = 0, index = 1;

42         

43         if(errs.size() == 4)

44             index = 3;

45             

46         temp = errs[0]->val;

47         errs[0]->val = errs[index]->val;

48         errs[index]->val = temp;

49     }

50 };

 

你可能感兴趣的:(Binary search)