递归

递归

递归的概念

递归:(英语:recursion)在计算机科学中是指一种通过重复将问题分解为同类的子问题而解决问题的方法。
递归的强大之处在于它允许用户用有限的语句描述无限的对象。因此,在计算机科学中,递归可以被用来描述无限步的运算,尽管描述运算的程序是有限的。

实例一 阶乘

错误的递归,永远不会结束

int factorial(int n){
    return n * factorial(n - 1);
}

有中止条件

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

实例二 斐波那契数列

int Fibonacci(int n){
    if (n <= 1)  
        return n;  
    else  
        return Fibonacci(n-1) + Fibonacci(n-2);  
}

实例三 汉诺塔

有三个塔A,B,C。N个大小不同的盘子放在A塔,自底向上按照从大到小的顺序排列。现在要求将盘子移到C塔但是要满足任何时刻大盘子不能放在小盘子上面。

基本思想分三步,先把上面的N-1个盘子经C移到B,然后将最底下的盘子移到C,再讲B上面的N-1个盘子经A移动到C。总的时间复杂度f(n)=2f(n-1)+1,所以f(n)=2^n-1

void hano(char a, char b, char c, int n) {
    if (n > 0) {
        hano(a, c, b, n-1);
        move(a, c);
        hano(b, a, c, n-1);
    }
}

void move(char a, char b)
{
    cout << a << "->" << b << endl;
}

实例四 求二叉树的深度

int depth(struct node* root)  
{  
    if (root == NULL)  
        return 0;  
    else {  
        int lDepth = depth(root->left);  //获取左子树深度  
        int rDepth = depth(root->right); //获取右子树深度  
        return lDepth>rDepth? lDepth+1: rDepth+1; //取较大值+1即为二叉树深度  
    }  
}

实例五 判断二叉树是否平衡

bool is_balanced(BinaryTreeNode* pRoot)
{
    if(pRoot == NULL) //基本情况,为空的话,返回true
        return true;

    int left = depth(pRoot->m_pLeft);
    int right = depth(pRoot->m_pRight);
    int diff = left - right; //计算左右子树深度之差
    if(diff > 1 || diff < -1) //如果深度之差大于1返回false
        return false;

    return is_balanced(pRoot->m_pLeft) && is_balanced(pRoot->m_pRight); //递归判断左右子树,注意是&&,即左右子树都必须是平衡的这棵二叉树才是平衡的
}

参考

Three passions, simple but overwhelmingly strong, have governed my life: the longing for love, the search for knowledge, and unbearable pity for the suffering of mankind
原文地址:https://www.cnblogs.com/s3abiscuit/p/7610656.html