后序遍历二叉树-非递归实现
2018-01-22 22:22 Dirichlet 阅读(545) 评论(0) 编辑 收藏 举报用栈实现非递归后序遍历二叉树
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication8 { class TreeNode { public TreeNode(string name, TreeNode right, TreeNode left) { this.Name = name; this.Left = left; this.Right = right; } public TreeNode Left { get; set; } public TreeNode Right { get; set; } public bool IsVisited { get; set; } public string Name { get; set; } } class Program { static void Main(string[] args) { /* 1 | | 2 3 | | | | 4 7 5 6 | | 8 9 */ List<TreeNode> nodeList = new List<TreeNode>(); for (int i = 1; i <= 9; i++) { nodeList.Add(new TreeNode($"{i} ", null, null)); } nodeList[0].Left = nodeList[1]; nodeList[0].Right = nodeList[2]; nodeList[1].Left = nodeList[3]; nodeList[1].Right = nodeList[6]; nodeList[2].Left = nodeList[4]; nodeList[2].Right = nodeList[5]; nodeList[6].Left = nodeList[7]; nodeList[6].Right = nodeList[8]; Recurse(nodeList[0]); } static void Recurse(TreeNode node) { Stack<TreeNode> stack = new Stack<TreeNode>(); stack.Push(node); while (stack.Count > 0) { var top = stack.Peek(); if ((top.Right == null && top.Left == null) || ((top.Left == null || top.Left.IsVisited == true) && (top.Right == null || top.Right.IsVisited == true)) ) { top = stack.Pop(); Console.Write(top.Name); top.IsVisited = true; continue; } if (top.Right != null) { stack.Push(top.Right); } if (top.Left != null) { stack.Push(top.Left); } } } } }
结果:
4 8 9 7 2 5 6 3 1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架