-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path99.recover_BST.cpp
49 lines (44 loc) · 1.16 KB
/
99.recover_BST.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//coding:utf-8
/***********************************************************
Program:
Description:
Shanbo Cheng: [email protected]
Date: 2016-08-10 14:03:25
Last modified: 2016-08-17 10:50:49
GCC version: 4.9.3
***********************************************************/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//inorder traverse, the first element is the one bigger than the successor
//second element is the one smaller the previous ones
//
#include "misc.h"
class Solution {
TreeNode* first;
TreeNode* second;
TreeNode* prev;
public:
void recoverTree(TreeNode* root) {
prev = new TreeNode(INT_MIN);
traverse(root);
swap(first->val, second->val);
}
void traverse(TreeNode* root) {
if(!root)
return;
traverse(root->left);
if (!first && prev->val >= root->val)
first = prev;
if (first && prev->val >= root->val)
second = root;
prev = root;
traverse(root->right);
}
};