Skip to content

Commit

Permalink
Update 99_Recover Binary Search Tree.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
veryordinary11 authored Mar 21, 2023
1 parent 8ded9b2 commit 19be55f
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions Binary Tree/99_Recover Binary Search Tree.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,41 @@ class Solution {
change_tree(root,sample_tree);
}
};

————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:

TreeNode* first = NULL;
TreeNode* second = NULL;
TreeNode* prev = new TreeNode(INT_MIN);

void Inorder(TreeNode* root){
if(root == NULL) return;

Inorder(root->left);

if(first == NULL && prev->val > root->val) first = prev;
if(first != NULL && prev->val > root->val) second = root;
prev = root;

Inorder(root->right);
}

void recoverTree(TreeNode* root) {
Inorder(root);
swap(first->val, second->val);
}
};

0 comments on commit 19be55f

Please sign in to comment.