99. 恢复二叉搜索树
题目描述
二叉搜索树中的两个节点被错误地交换。
请在不改变其结构的情况下,恢复这棵树。
示例 1:
输入: [1,3,null,null,2]
输出: [3,1,null,null,2]
示例 2:
输入: [3,1,4,null,null,2]
输出: [2,1,4,null,null,3]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/recover-binary-search-tree
解
思路:递归,在二叉搜索树中找到出问题的两个节点,交换即可。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void recoverTree(struct TreeNode* root){
if(root == NULL)return;
int leftmax = maxvalTree(root->left);
int rightmin = minvalTree(root->right);
if(leftmax > root->val && rightmin < root->val){
int temp = leftmax;
switchATreenode(root->left,leftmax,rightmin);
switchATreenode(root->right,rightmin,temp);
return;
}
if(leftmax > root->val){
switchATreenode(root->left,leftmax,root->val);
root->val = leftmax;
return;
}
if(rightmin < root->val){
switchATreenode(root->right,rightmin,root->val);
root->val = rightmin;
return;
}
recoverTree(root->left);
recoverTree(root->right);
return;
}
int maxvalTree(struct TreeNode* root){
if(root == NULL)return -60000;
return fmax(fmax(maxvalTree(root->left),maxvalTree(root->right)),root->val);
}
int minvalTree(struct TreeNode* root){
if(root == NULL)return 60000;
return fmin(fmin(minvalTree(root->left),minvalTree(root->right)),root->val);
}
void switchATreenode(struct TreeNode* root, int val, int newval){
if(root == NULL)return;
if(root->val == val){
root->val = newval;
return;
}
switchATreenode(root->left,val,newval);
switchATreenode(root->right,val,newval);
return;
}