儿茶搜索树的生长,树的高度,树的最大值,查找某个元素是否在树种,统计元素出现的个数,层序遍历

#include<iostream>
#include<queue>
using  namespace std;
typedef struct node
{
int data;
struct node* left;
struct node* right;
}Node;
typedef struct tree
{
Node* root=NULL;
}Tree;
void insert(Tree* tree,int value)
{
Node* node=(Node*)malloc(sizeof(Node));
node->data = value;
node->left = NULL;
node->right = NULL;
if (tree->root == NULL)
{
tree->root = node;
}
else
{
Node* temp = tree->root;
while (temp != NULL)
{
if (value < temp->data)
{
if (temp->left == NULL)
{
temp->left = node;
return;//找空位插进去,插进去后就停止位置搜索
}
else
{
temp = temp->left;
}
}
else
{
if (temp->right == NULL)
{
temp->right = node;
return;
}
else
{
temp = temp->right;
}
}
}
}
}
void preorder(Node* node)
{
if (node != NULL)
{
cout << node->data<<' ';
preorder(node->left);
preorder(node->right);
}
}
void inorder(Node* node)
{
if (node != NULL)
{
inorder(node->left);
cout << node->data<<' ';
inorder(node->right);
}
}
int get_height(Node* node)
{
if (node == NULL)
{
return 0;
}
else
{
int left=get_height(node->left);//好生猛
int right=get_height(node->right);//好生猛
int max = left;
if (max < right)
max = right;
return max + 1;//当前节点告诉等于左右子树的最大高度加1
}
}
int get_max(Node* node)
{
if (node == NULL)
return -1;
else
{
int left = get_max(node->left);//生猛写递归大法好
int right = get_max(node->right);
int center = node->data;
int max=center;
if (max < left)
max = left;
if (max < right)
max = right;
return max;
}
}
int find_sum(Node* node,int val)
{
if (node == NULL)
return 0;
else
{
bool flag = false;
if (node->data == val)
flag = true;//查找个数
int left=find_sum(node->left, val);
int right = find_sum(node->right, val);
if (flag == true)
return(left + right + 1);
else
return (left+right);
}
}
bool find(Node* node, int val)
{
if (node == NULL)
{
return false;
}
else
{
if (node->data == val)
{
return true;
}
else
{
bool left = find(node->left, val);
bool right = find(node->right, val);
return(left || right);
}
}
}
void cxbb(Node* node)
{
if (node == NULL)
{
return;
}
else
{
queue<Node*> q;
q.push(node);
while (!q.empty())
{
cout << q.front()->data<<' ';
if (q.front()->left!=NULL)
q.push(q.front()->left);
if (q.front()->right!=NULL)
q.push(q.front()->right);
q.pop();
}
}
}
int main()
{
Tree tree;
int arr[7] = { 6, 3, 8, 2, 5, 1, 7 };
for (int i = 0; i < 7; i++)
{
insert(&tree, arr[i]);
}
preorder(tree.root);
cout << endl;
//inorder(tree.root);
//cout << endl;
//cout << get_height(tree.root) << endl;
//cout << get_max(tree.root)<<endl;
//cout << find_sum(tree.root, 9) << endl;
//cout << find(tree.root, 8) << endl;
cxbb(tree.root);
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值