递归、非递归~二叉树

1.递归代码:

#include<iostream>
using namespace std;


int common(int x , int y){
    if(x == y)
    return x;
    else if(x > y)
    return common(x/2, y);
    else
    return common(x, y/2);
}
int main()
{
    int x, y;
    cout << "Enter two numbers: " << endl;
    cin >> x >> y;
    cout << common(x, y) << endl;
    return 0;
}

运行结果:

Enter two numbers:
10 4
2


Process returned 0 (0x0)   execution time : 3.552 s
Press any key to continue.

2.非递归代码:

#include<iostream>
using namespace std;

int main()
{
    int x, y;
    cout << "Enter two numbers : " << endl;
    cin >> x >> y;
    int m, n;       //设置临时变量,
    m = x;
    n = y;
    while(m != n)
    {
        if(m > n)
            m = m/2;
        else
            n = n/2;
    }
    cout << m << endl;
    return 0;
}


运行结果:

Enter two numbers :
10 4
2

Process returned 0 (0x0)   execution time : 2.873 s
Press any key to continue.

比较分析:

由以上的运行结果来看,非递归的执行效率要高些。

一般而言,递归时间花销主要是函数的递归调用上,其空间开销大。

非递归效率一般要比递归高很多,但是要去模拟栈,必须得有循环,因此,时间开销增大。

所以递归算法用空间复杂度分析较合适,而改成的非递归算法用时间复杂度分析较合适。各有所长,根据实际情况来选择……


同时欢迎提出宝贵意见,以帮助我改进,不胜感激!!!

——桑海整理



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值