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?
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void recoverTree(TreeNode* root) { stack<TreeNode*> s; TreeNode *p = root, *last = NULL, *p1 = NULL, *p2 = NULL; while(p || !s.empty()) { while(p) { s.push(p); p = p->left; } if(!s.empty()) { p = s.top(); s.pop(); if(last && last->val >= p->val) { p2 = p; if(!p1) p1 = last; else break; } last = p; p = p->right; } } swap(p1->val, p2->val); } };
时间: 2024-11-06 12:22:14