用栈实现递归算法(第一版)
学习使用,先用二叉树后序遍历写了个 斐波那契数的例子,后台陆续更新更好的算法,最新在学《算法导论》,开始有点困难,不过不急,慢慢来。。。一天,一周,一个月一个算法,弄明白了,比什么都强!!
这段代码没有解释,不久会更新,先看着代码哈
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace TEST
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.Write(GetFoo(10));
- Console.Read();
- }
- //
- static long GetFoo(int n)
- {
- if (IsLeaf(n))
- {
- return GetLeafvalue(n);
- }
- //结果保存栈
- Stack<long[]> resultStack = new Stack<long[]>();
- //临时结果数组
- long[] tempResultArry = InitTempResultArry();
- //压入临时结果数组
- resultStack.Push(tempResultArry);
- //临时节点栈
- Stack<int> tempNodeStack = new Stack<int>();
- //压入根节点
- tempNodeStack.Push(n);
- //遍历临时节点
- while (tempNodeStack.Count > 0)
- {
- tempResultArry = resultStack.Last();
- int branchIndex = GetNodeBranchIndex(tempResultArry);
- //当前节点遍历完成
- if (branchIndex == -1)
- {
- if (resultStack.Count == 1)
- {
- break;
- }
- else
- {
- tempNodeStack.Pop();
- resultStack.Pop();
-
- //把结果赋值给上层
- //tempResultArry = resultStack.Last();
- long tempResult = CalculateResult(tempResultArry);
- tempResultArry[1] = tempResultArry[0];
- tempResultArry[0] = tempResult;
- }
- }
- else
- {
- //没完成,得到要遍历的下一个节点
- int currentNode = tempNodeStack.First();
- int nextNode = GetSubNode(currentNode, branchIndex);
- if (IsLeaf(nextNode))
- {
- tempResultArry[branchIndex] = GetLeafvalue(nextNode);
- }
- else
- {
- tempNodeStack.Push(nextNode);
- resultStack.Push(InitTempResultArry());
- }
- }
- }
- return CalculateResult(resultStack.First());
- }
- //
- static bool IsLeaf(int n)
- {
- return n < 3;
- }
- //
- static int GetNodeBranchIndex(long[] tempNodeResultArry)
- {
- for (int i = 0; i < tempNodeResultArry.Length; i++)
- {
- if (tempNodeResultArry[i] == -1)
- {
- return i;
- }
- }
- return -1;//表示没有遍历完成
- }
- //
- static int GetSubNode(int node, int branchIndex)
- {
- return node - branchIndex - 1;
- }
- //
- static long GetLeafvalue(int n)
- {
- return 1;
- }
- //
- static long[] InitTempResultArry()
- {
- long[] tempResultArry = new long[2];
- for (int i = 0; i < 2; i++)
- {
- tempResultArry[i] = -1;
- }
- return tempResultArry;
- }
- static long CalculateResult(long[] tmpResults)
- {
- long retValue = 0;
- for (int i = 0; i < 2; i++)
- {
- retValue += tmpResults[i];
- }
- return retValue;
- }
- }
- }
============ 欢迎各位老板打赏~ ===========
与本文相关的文章
- · 用栈实现递归算法(第一版)
- · The instance of entity type ‘Customer’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked.
- · .NET8实时更新nginx ip地址归属地
- · 解决.NET Blazor子组件不刷新问题
- · .NET8如何在普通类库中引用 Microsoft.AspNetCore
- · .NET8 Mysql SSL error
- · ASP.NET Core MVC的Razor视图渲染中文乱码的问题
- · .NETCORE 依赖注入服务生命周期
- · asp.net zero改mysql
- · .NET5面试汇总
- · .Net连接Mysql数据库的Convert Zero Datetime日期问题
- · vue使用element-ui中的Message 、MessageBox 、Notification