考研算法
题目
题目链接 中序遍历有序的二叉树为二叉排序树
题目要求
你需要写一种数据结构,来维护一些数,其中需要提供以下操作:
- 插入数值 xx。
- 删除数值 xx。
- 输出数值 xx 的前驱(前驱定义为现有所有数中小于 xx 的最大的数)。
- 输出数值 xx 的后继(后继定义为现有所有数中大于 xx 的最小的数)。
代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF=500000;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int _val) : val(_val),left(NULL),right(NULL) {}
}*root;
void insert(TreeNode* &root,int x)//插入
{
if (!root) root=new TreeNode(x);//如果节点不存在,则直接生成
if (root->val==x) return;//若存在,则返回
else if (x > root->val) insert(root->right,x);//大的在右边,小的在左边
else insert(root->left,x);
}
void remove(TreeNode* &root,int x)//删除
{
if (!root) return;
if (x>root->val) remove(root->right,x);
else if (x<root->val) remove(root->left,x);
else//找到节点了
{
if (!root->left && !root->right) root=NULL;//若为叶子节点,则直接删去
else if (!root->left) root=root->right;//无左节点,但有右节点,直接设为右节点
else if (!root->right) root=root->left;
else//有左右子节点,则寻找左边最大的数,然后将此节点的值设为左边最大数,再删去左边最大节点
{
auto p=root->left;
while (p->right) p=p->right;
root->val=p->val;
remove(root->left,p->val);
}
}
}
int search3(TreeNode* &root,int x)//寻找小于x的最大的数
{
if (!root) return -INF;
if (root->val>=x) return search3(root->left,x);//小于根节点,向左节点寻找
else return max(root->val,search3(root->right,x));//使用max主要是为了防止当前树中只有当前节点小于x,而右子树全部大于x
}
int search4(TreeNode* &root,int x)
{
if (!root) return INF;
if (root->val<=x) return search4(root->right,x);
else return min(root->val,search4(root->left,x));
}
int main()
{
int n;
cin>>n;
while(n--)
{
int opt,x;
cin>>opt>>x;
if (opt==1) insert(root,x);
if (opt==2) remove(root,x);
if (opt==3) cout<<search3(root,x)<<endl;
if (opt==4) cout<<search4(root,x)<<endl;
}
return 0;
}
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
n=int(input())
def insert(root,x):
if not root:
root=TreeNode(x)
if (root.val==x) :return
elif (root.val<x) :insert(root.right,x)
elif (root.val>x) :insert(root.left,x)
def remove(root,x):
if not root:return
if (root.val<x) :remove(root.right,x)
elif (root.val>x) :remove(root.left,x)
else:
if (root.left==None and root.right==None) :root=None
elif (root.left==None) :root=root.right
elif (root.right==None) :root=root.left
else:
p=root.left
while(p.right): p=p.right
root.val=p.val
remove(root.left,p.val)
def search3(root,x):
if root==None:return -500000
if x<=root.val: search3(root.left,x)
else :return max(root.val,search3(root.right,x))
def search4(root,x):
if root==None :
return 500000
if x>=root.val:
search4(root.right,x)
else :
return min(root.val,search4(root.left,x))
for i in range(n):
opt,x=map(int,input().split())
if i==0:
y=TreeNode(x)
if opt==1:
insert(y,x)
if opt==2:
remove(y,x)
if opt==3:
print(search3(y,x))
if opt==4:
print(search4(y,x))
知识点
主要用递归解决
求助
python的过不了,来个大神教教我