问题描述 wo 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? Subscribe to see which companies asked this question.
解决思路 使用inorder遍历的办法,因为在二叉查询树时,inorder遍历会满足遍历到的节点是有序的,而此时为升序,所以我们只要找到两个不满足pre->val < cur->val的节点就可以了。
代码
/** * 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: TreeNode* first=NULL; TreeNode* second=NULL; TreeNode* pre = new TreeNode(INT_MIN); void recoverTree(TreeNode* root) { helper(root); int tmp = first->val; first->val = second->val; second->val = tmp; } void helper(TreeNode* root) { if (root == NULL) return; helper(root->left); if (!first && pre->val >= root->val) first = pre; if (first && pre->val >= root->val) {second = root; } pre = root; helper(root->right); }};新闻热点
疑难解答