Hdu3999 The order of a Tree

本文介绍了一种构建二叉搜索树的方法,并实现了先序遍历输出节点值的功能。通过递归的方式添加节点并确保树的特性得到维持,最后利用深度优先搜索策略完成遍历。

题意:就是构建一棵树,然后先序输出就行了

代码如下:

#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stdlib.h>
#include<math.h>
#include<vector>
#include<queue>
using namespace std;
struct Node
{
    bool have_value;
    int v;
    Node*left,*right;
    Node():have_value(false),left(NULL),right(NULL) {}

};
vector<int> ans;
Node* root;
Node*newnode()
{
    return new Node();
}
void addnode(int k,Node*root)
{
    Node* u=root;
    if(u->left==NULL)
        u->left=newnode();
    if(u->right==NULL)
        u->right=newnode();
    if(k<u->v&&!u->left->have_value)
    {
        u->left->v=k;
        u->left->have_value=true;
        return ;
    }
    else if(k>=u->v&&!u->right->have_value)
    {
        u->right->v=k;
        u->right->have_value=true;
        return;
    }
    else if(k<u->v&&u->left->have_value)
    {
        u=u->left;
        addnode(k,u);
    }
    else if(k>=u->v&&u->right->have_value)
    {
        u=u->right;
        addnode(k,u);
    }
}

void dfs(Node *u)
{
    if(u == NULL || !u->have_value) return ;

        ans.push_back(u->v);
    dfs(u->left);
    dfs(u->right);
}

int main()
{
    //freopen("in.txt","r",stdin);
    int n,k,nod;
    while(scanf("%d",&n) != EOF) {
        scanf("%d",&nod);
        root=newnode();
        root->v=nod;
        root->have_value=true;
        for(int i=1; i<n; i++)
        {
            scanf("%d",&k);
            addnode(k,root);
        }
        ans.clear();
        dfs(root);
        vector<int>::iterator it;
        for( it = ans.begin(); it < ans.end()-1; it++ )
            printf("%d ",*it);
        printf("%d\n",ans.back());
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值