首页 > 代码库 > 【LeetCode】Recover Binary Search Tree
【LeetCode】Recover Binary Search Tree
Recover Binary Search Tree
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?
基本知识点:二叉搜索树的中序遍历就是升序序列。
因此不满足升序的两个点就是互换的地方。设置头结点INT_MIN来保证第一次满足。
问题在于,不满足升序的地方最多一共会出现4次,例如:
INT_MIN, 4, 2, 5, 1, 3
> <
涉及到4,2,1,3
稍作分析即可知道,第一次出现反常(>)意味着前一个结点有问题,而第二次出现反常(<)
意味着后一个结点有问题。因此交换这两个问题节点即可。
有个小问题需要注意:如果一共只有两个节点,那么两次反常在同一次比较中出现了。
为了处理这种情况,我们在第一次反常时,就把后一个结点也设置为问题节点,后续再不断更新。
/** * Definition for binary tree * 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* prev = new TreeNode(INT_MIN); void recoverTree(TreeNode *root) { inOrder(root); int tmp = first->val; first->val = second->val; second->val = tmp; } void inOrder(TreeNode* root) { if(!root) return; inOrder(root->left); if(root->val < prev->val) {//invalid prev if(!first) //we determine the first because the prev is unusually big //attention, the first can be updated only once first = prev; //we determine the second because the root is unusually small //attention, the second can be updated anytime second = root; } else prev = root; //valid prev inOrder(root->right); }};
【LeetCode】Recover Binary Search Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。