Problem P01. [算法课分治] 最大二叉树

这将会是一个系统性的算法学习专栏,编程语言为C++,适用于刚开始学算法的学生和博友,建议需要的朋友收藏订阅,是免费的,希望对大家能够有所帮助,本身的原文我发在博客园中,现在正在迁移过来,预计几天内能完成迁移。

在这里插入图片描述

需要注意的:

  1. scanf()的返回值是 EOF,输入结束
  2. 通过指针指向左右子树的二叉树构建
#include<iostream>
#include<bits/stdc++.h>
#include<cstdio>

using namespace std;
struct node
{
    int data;
    node *leftchild;
    node *rightchild;

    node(const int& x){
        data = x;
        leftchild=NULL;
        rightchild=NULL;
    }
};

int nums[1005];
node* buildtree(int left, int right){
    if (left>right) return NULL;
    int idmax = left, valmax = nums[idmax];
    for (int i = left+1; i <= right; i++){
        if (valmax<nums[i]){
            valmax = nums[i];
            idmax = i;
        }
    }
    node* root = new node(valmax);
    //cout << root->data << endl;
    root->leftchild = buildtree(left, idmax-1);
    root->rightchild = buildtree(idmax+1, right);
    return root;
}

void qiansearch(node *root)
{
    printf("%d ", (root->data));
    if (root->leftchild==NULL && root->rightchild==NULL){
        return;
    }
    if (root->leftchild==NULL){
        printf("null ");
    }else {
        qiansearch(root->leftchild);
    }
    if (root->rightchild==NULL){
        printf("null ");
    }else {
        qiansearch(root->rightchild);
    }
    return;
}

int main()
{
    int n;
    for(n = 0; 1; n++)
    {
        int ret = scanf("%d", &nums[n]);
        if (ret == EOF)break;
    }
    n--;
    node *root = buildtree(0, n);
    qiansearch(root);
    return 0;
}
  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值