当前位置: 代码迷 >> 综合 >> 搜索二叉树(二叉排序树)的插入 中序遍历
  详细解决方案

搜索二叉树(二叉排序树)的插入 中序遍历

热度:5   发布时间:2023-12-21 00:11:05.0

给出 n 个数,建成一棵搜索二叉树

#include<bits/stdc++.h>
using namespace std;struct node{
    int value;node *left;node *right;
};void insert(node *root, int x)
{
    if(x > root -> value){
    if(root -> right != NULL) insert(root -> right, x);else{
    node *tmp = new node();tmp -> left = NULL;tmp -> right = NULL;tmp -> value = x;root -> right = tmp;}}else{
    if(root -> left != NULL) insert(root -> left, x);else{
    node *tmp = new node();tmp -> left = NULL;tmp -> right = NULL;tmp -> value = x;root -> left = tmp;}}
}void ZB(node *root)
{
    if(root != NULL){
    if(root -> left != NULL) ZB(root -> left);cout<<root -> value;if(root -> right != NULL) ZB(root -> right);}
}int main()
{
    int n;node *tree = new node();scanf("%d",&n);int x;scanf("%d",&x);tree -> left = tree -> right = NULL;tree -> value = x;for(int i=2;i<=n;i++){
    scanf("%d",&x);insert(tree, x);}ZB(tree);return 0;
}
  相关解决方案