深层递归的优化

深层递归的优化

using System.Collections;

Stack st = new Stack();

//二叉树中序遍历
//递归。。。。
List<int> list = new List<int>();
 List<int> inorderTraversal(TreeNode root)
{
    if (root == null)
        return list;
    inorder(root.left);
    list.Add(root.val);
    inorder(root.right);
    return list;
}
 void inorder(TreeNode root)
{
    if (root == null)
        return;
    inorder(root.left);
    list.Add(root.val);
    inorder(root.right);
}


foreach (var item in inorderTraversal(new TreeNode(1, null, new TreeNode(2, new TreeNode(3, null, null), null))))
{
    Console.WriteLine(item);
}


//显式栈:



List<int> inorderTraversal1(TreeNode root)
{
    List<int> res = new List<int>();
    LinkedList<TreeNode> stk = new LinkedList<TreeNode>();
    while (root != null || !(stk.Count == 0))
    {
        while (root != null)
        {
            stk.AddLast(root);
            root = root.left;
        }
        root = stk.Last();
        stk.RemoveLast();
        res.Add(root.val);
        root = root.right;
    }
    return res;
}

Console.WriteLine("======================");

foreach (var item in inorderTraversal1(new TreeNode(1, null, new TreeNode(2, new TreeNode(3, null, null), null))))
{
    Console.WriteLine(item);
}


//斐波那契
int Fib(int n)
{
    if (n == 1 || n == 2) return 1;
    else return Fib(n - 1) + Fib(n - 2);
}
Console.WriteLine("===========斐波那契===========");

Console.WriteLine(Fib(16));

//使用缓存

int FibCache(int n)
{
    int[] cache = { 0, 1, 1 };

    int _fib(int n)
    {
        if (cache[n] == 1) return cache[n];

        cache[n] = _fib(n - 1) + _fib(n - 2);

        return cache[n];

    }
    return _fib(n);
}

Console.WriteLine("===========斐波那契2===========");

Console.WriteLine(Fib(16));

public class TreeNode
{
    public int val { get; set; }
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}


结果:

1
3
2
======================
1
3
2
===========斐波那契===========
987
===========斐波那契2===========
987

D:\Csharp\ConsoleTest1\ConsoleTest1\bin\Debug\net6.0\ConsoleTest1.exe (进程 2356)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值