99. Recover Binary Search Tree
Hard
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2] 1 / 3 \ 2 Output: [3,1,null,null,2] 3 / 1 \ 2
Example 2:
Input: [3,1,4,null,null,2] 3 / \ 1 4 / 2 Output: [2,1,4,null,null,3] 2 / \ 1 4 / 3
Follow up:
- A solution using O(n) space is pretty straight forward.
- Could you devise a constant space solution?
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 | /** * 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: void recoverTree(TreeNode* root) { TreeNode *e1 = NULL, *e2 = NULL, *prev = NULL; int lb = INT_MIN; dfs(root, prev, e1, e2, lb); swap(e1->val, e2->val); } void dfs(TreeNode* root, TreeNode *&prev, TreeNode *&e1, TreeNode *&e2, int &lb){ if(!root) return; dfs(root->left, prev, e1, e2, lb); if(root->val<lb){ if(!e1){ e1 = prev; } e2 = root; } lb = max(root->val, lb); prev = root; dfs(root->right, prev, e1, e2, lb); } }; |
No comments:
Post a Comment