二叉树实现

#include <cstdio>

struct node {
int key;//关键字
node *left;//左儿子
node *right;//右儿子
node *parent;//父节点
node()
{
key = 0;
left = NULL;
right = NULL;
parent = NULL;
}
};

//中序遍历二叉树
void in_order_walk(node *root)
{
if (root == NULL)
{
return;
}
in_order_walk(root->left);
printf("%d ",root->key);
in_order_walk(root->right);
}

//插入新节点
void insert(node **root, int key)//root采用传址的方法,才能zheng'zhen
{
node *y = NULL;
node *x = *root;
//找插入点,即找一个为空的位置
while (x != NULL)
{
y = x;
x->key > key ? x = x->left : x = x->right;
}
node *newNode = new node();
newNode->key = key;
newNode->parent = y;
//树为空
if (y == NULL)
{
*root = newNode;
}
//更改插入节点的父节点的儿子指针
else
{
y->key > newNode->key ? y->left = newNode : y->right = newNode;
}
}

//以节点t为根的子树的最大关键字
int max_num(node *t)
{
while (t->right != NULL)
{
t = t->right;
}
return t->key;
}

//以节点t为根的子树的最小关键字
int min_num(node *t)
{
while (t->left != NULL)
{
t = t->left;
}
return t->key;
}

//节点t的直接后继
node* successor(node *t)
{
//右子树不为空时
if (t->right != NULL)
{
return t->right;
}
//右子树为空时,就找一个祖先节点,且该节点包含有左儿子
node *y = t->parent;
while (y != NULL && t == y->right)
{
t = y;
y = y->parent;
}
return y;
}

//删除节点t
void delete_node(node **root, node *t)
{
node *y == NULL;
node *x == NULL;
//如果左儿子和右儿子同时有,则删除t的后继节点,再将t的key值改为其后级节点的值,否则直接删除节点,修改父子指正即可
if (t->left == NULL || t->right = NULL)
{
y = t;
}
else
{
y = successor(t);
}
//y最多只会拥有一个儿子,不解释
if (y->left != NULL)
{
x = y->left;
}
else
{
x = y->right;
}
//修改删除节点的子结点的父指针
if (x != NULL)
{
x->parent = y->parent;
}
//修改删除节点的父节点的儿子指针
if (y->parent != NULL)
{
&root = x;
}
else
{
y == y->parent->left ? y->parent->left = x : y->parent->right = x;
}
if (y->key != t->key)
{
t->key = y->key;
}
return;
}

//在一t为根节点为根的子树中查找值为key的节点
node* search(node *t, int key)
{
while (t != NULL && t->key != key)
{
if (t->key > key)
{
t = t->left;
}
else
{
t = t->right;
}
}
return t;
}

int main()
{
node *root = NULL;
int data;
while (scanf("%d",&data) && data != 0)
{
insert(&root, data);
}
in_order_walk(root);
system("pause");
return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值