递归c ++函数打印出斐波纳契树的元素

问题描述 投票:0回答:1

到目前为止,我已经能够使用递归打印出斐波那契序列。例如,序列中的前6个术语(包括第0个术语)是:

6

13 8 5 3 2 1 1

但我不知道我应该怎么用它来打印出整个斐波纳契树。当程序输入为6时,它应该打印:

6
13 8 5 3 2 1 1 1 2 1 1 3 2 1 1 1 5 3 2 1 1 1 2 1 1

我的代码到目前为止是:

#include <iostream>
#include <math.h>
#include <vector>
#include <string>

using namespace std;

std::vector<int> list;

int fib(int num);

int main() {
    int input, depth = 0, leafs = 0, size = 0;

    cin >> input;
    int temp = input;

    while (temp >= 0) {
        cout << fib(temp) << " ";
        temp--;
    }


    return 0;
}

int fib(int n) {
    if (n <= 1) {
        return 1;
    } else {
        return fib(n-1) + fib(n-2);
    }
}
c++ recursion fibonacci
1个回答
1
投票

如果要打印所有内容,还需要所有功能来打印所有内容:

int fib(int n) {
    if (n <= 1) {
        std::cout << 1 << " ";
        return 1;
    } else {
        int f1 = fib(n-1);
        int f2 = fib(n-2);
        std::cout << f1 + f2 << " ";
        return f1 + f2;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.