二叉树创建,遍历和求最大值

来源:互联网 发布:数据库能干什么 编辑:程序博客网 时间:2024/06/08 12:14

这里写图片描述

#include<iostream>using namespace std;//char nums[11] = { 'a', 'b', '#', 'd', '#', '#', 'c', '#', 'e', '#', '#' };int nums[11] = { 10, 9, -1, 17, -1, -1, 3, -1, 5, -1, -1 };int i = 0;//int max = 0;struct TreeNode{    int key;    TreeNode* left;    TreeNode* right;};TreeNode* CreateTree(){    TreeNode* T = new TreeNode;    int a=nums[i++];    /*cout << "输入节点的值" << endl;    cin >> a;*/    if (a == -1)        T = nullptr;    else    {        T->key = a;        T->left = CreateTree();        T->right = CreateTree();    }    return T;}void prvisit(TreeNode *T){    if (T == nullptr)    {        return;    }    cout << T->key << endl;    prvisit(T->left);    prvisit(T->right);}void maxPoint(TreeNode* T,int &max){    if (T == nullptr)        return;    if (T->key>max)    {        max = T->key;    }    maxPoint(T->left,max);    maxPoint(T->right,max);}int main(){    TreeNode *T;    int max = 0;    T = CreateTree();    prvisit(T);    maxPoint(T,max);    cout << max << endl;}
0 0
原创粉丝点击