博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用栈实现递归算法(第一版)
阅读量:7076 次
发布时间:2019-06-28

本文共 3556 字,大约阅读时间需要 11 分钟。

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
resultStack = new Stack
(); //临时结果数组 long[] tempResultArry = InitTempResultArry(); //压入临时结果数组 resultStack.Push(tempResultArry); //临时节点栈 Stack
tempNodeStack = new Stack
(); //压入根节点 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(); //branchIndex = GetNodeBranchIndex(tempResultArry); //把结果赋值给上层 //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; } }}

 

转载于:https://www.cnblogs.com/longle/archive/2013/02/17/2914365.html

你可能感兴趣的文章
监控利器Nagios之二:Nagios的细致介绍和监控外部服务器的私有信息
查看>>
QoS技术入门(实操必须掌握的基本理论)
查看>>
老男孩浅谈如何看待运维?
查看>>
linux系统基础调优32条技巧
查看>>
华为USG统一安全边界网关的设计、演示、经验鉴证实评-卷A
查看>>
我的友情链接
查看>>
Lync和Exchange 2013集成PART6:OWA集成IM
查看>>
腾讯云、阿里云都“服”了,云容灾你还迟疑什么?
查看>>
【Hibernate框架开发之九】Hibernate 性能优化笔记!(遍历、一级/二级/查询/缓存/乐观悲观锁等优化算法)...
查看>>
[C# 基础知识系列]专题十一:匿名方法解析
查看>>
zabbix自动添加删除主机的python脚本
查看>>
《Java从小白到大牛精简版》——前言
查看>>
坑爹的生活,源于你的工作谁都能干
查看>>
客户端网络库实现真的很简单吗?
查看>>
用百度推荐提升PV和收益的小方法
查看>>
300元成松松写字团10天好基友,值吗?
查看>>
不用Visual Studio,5分钟轻松实现一张报表
查看>>
FreeBSD下安装配置Hadoop集群(四)
查看>>
技术人员,请注意那些被你忽略的重要事情
查看>>
WINDOWS上数据灾难后专业的现场保护方法
查看>>