题目
题解
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。二叉搜索树作为一种经典的数据结构,它既有链表的快速插入与删除操作的特点,又有数组快速查找的优势;所以应用十分广泛,例如在文件系统和数据库系统一般会采用这种数据结构进行高效率的排序与检索操作。(开源:百度百科)
简而言之,就是左子树的值一定要比根节点小,右子树的值一定要比根节点大。
通过探索发现,如果将二叉查找树进行中序排列,那么生成的列表将是升序排列,我们可以依据这个解题。
注:三种排列方式
代码段
本次解题采用了最为老实的办法,一步步,先遍历列表然后去比较大小,代码参考了力扣用户:ni8fun的讲解后自己敲写
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int lenth(struct TreeNode*root){
if(!root) return 0;
return lenth(root->left)+lenth(root->right)+1;
}
void list(struct TreeNode* root,int *arr,int *b){
if(!root) return ;
list(root->left,arr,b);
arr[(*b)++] = root->val;
list(root->right,arr,b);
return ;
}
bool replace(struct TreeNode* root ,int x,int y,int count){
if(!root) return false;
if(root->val == x){
root->val = y;
if(count==1) return true;
else count ++;
}
else {
if(root->val == y){
root->val = x;
if(count==1) return true;
else count ++;
}
}
if(replace(root->left, x, y, count)) return true;
if(replace(root->right, x, y, count)) return true;
return false;
}
void recoverTree(struct TreeNode* root){
if(!root || (!root->left && !root->right));
int *arr = (int*)malloc(lenth(root)*sizeof(int));
int num = 0;
int *b = #
//中序便利
list(root,arr,b);
//排序
int x = 0;
int y = 0;
for (int i =0;i<*b-1;i++){
if(arr[i]>arr[i+1]){
y = arr[i+1];
if (x == 0) x = arr[i];
}
}
//替换
replace(root,x,y,0);
return ;
}
总结
这个题其实记住了二叉搜索树的中序排列是升序排列就有了思路,剩下的全靠实操,长路慢慢,自己太菜