C++學習筆記-7-遞歸函數

遞歸函數頗有意思,要講一下。好比要計算n!咱們就這樣定義:ios

#include <iostream>

using namespace std;


double factorial(double n)
{
    if(n==0)return 1;
    else
    {
        return n*factorial(n-1);
    }
}


int main()
{
    cout << "Hello world!" << endl;
    cout<<factorial(100)<<endl;
    return 0;
}

 

這個遞歸函數在二叉樹的遍歷中使用的最多,並且很方便:函數

template <class T>spa

void preorder(T *root){遞歸

if(root!==NULL){io

cout<<root->data<<"-->"class

preorder(root->leftleaf);stream

preorder(root->rightleaf);二叉樹

}遍歷

}co

相關文章
相關標籤/搜索