2021-11-09

Eine Bessere Zukunft
今天做的一道学校里的C++的作业题

题目:将Fibonacci用树的形式表示出来。

Fibonacci数列:
f ( 0 ) = 1 f ( 1 ) = 1 f ( n ) = f ( n − 1 ) + f ( n − 2 ) , n > = 2 f(0)=1\\ f(1) = 1\\ f(n) = f(n-1)+f(n-2),n >=2 f(0)=1f(1)=1f(n)=f(n1)+f(n2),n>=2
也就是说我们输入3 的话,那么就可以生成这样的树

  • 2021-11-09_第1张图片
    我们此时要求用前序法遍历树,并且输出树的大小,和树的高度以及树的叶子。
    示例:
如果输入是 3的话,那么输出如下:
Call tree in pre-order: 3 2 1 1 1
Call tree size: 5
Call tree depth: 3
Call tree leafs: 3

代码如下

#include
using namespace std;


//先利用结构体定义结点
struct Node   
{
    int value;
    Node *left;
    Node *right;
};

//定义树的根
struct Tree  
{
    Node *root;
};

//建立树
int constructTree(Node *node,int label)
{
    if (label >= 2)
    {
        //给左结点动态分配内存
        Node *left = (Node *)malloc(sizeof(Node));
        //给右结点动态分配内存
        Node *right = (Node *)malloc(sizeof(Node));
        //左节点的值,等于左节点的递归
        left->value = constructTree(left,label-1);
        right->value = constructTree(right,label-2);
        node->left = left;
        node->right = right;
        //结点的值等于左节点的值加上右结点的值
        node->value = left->value + right->value;
        return node->value;
    }
    else if (label == 1||label == 0)
    {
        node->left = NULL;
        node->right = NULL;
        node->value = 1;
        return 1;
    }
    else 
        return 0;
}

void createTree(Tree *tree,int label)
{
    //给结点分配内存
    Node *node = (Node *)malloc(sizeof(Node));
    //结点的值为创建树的返回值
    node->value = constructTree(node,label);
    //把树的根的值置为结点的值
    tree->root = node;
}

//前序遍历二叉树
void callTreePreOrder(Node *node)
{
    if(node == NULL)
    {
        return;
    }

    cout << node->value <<" ";
    if(node->left !=NULL)
        callTreePreOrder(node->left);
    if(node->right !=NULL)
        callTreePreOrder(node->right);
}

int callTreeSize(Node *root)
{
    if(root != NULL)
        return 1+callTreeSize(root->left)+callTreeSize(root->right);
    else    
        return 0;
}

int callTreeDepth(Node *node)
{
    if(node !=NULL)
    {
        int left_depth = callTreeDepth(node->left);
        int right_depth = callTreeDepth(node->right);
        return left_depth > right_depth ? left_depth + 1: right_depth + 1;
    }
    else{
        return 0;
    }
}

int callTreeleaves(Node *node)
{
    if(node !=NULL)
    {
        if(node->left == NULL && node->right==NULL)
            return 1;
        return callTreeleaves(node->left)+callTreeleaves(node->right);
    }
    else
    {
        return 0;
    }
}

int main()
{
    int n;
    cin >> n;
    Tree *tree = new Tree;
    tree->root = NULL;
    createTree(tree,n);
    cout<<"Call tree in pre-order: ";
    callTreePreOrder(tree->root);
    cout<<endl;
    cout<<"Call tree size: "<< callTreeSize(tree->root)<<endl;
    cout << "Call tree depth: " << callTreeDepth(tree->root) << endl;
    cout << "Call tree leafs: " << callTreeleaves(tree->root) << endl;
}

你可能感兴趣的:(c++,数据结构)