C#先序遍历2叉树(非递归)
找了下先序遍历二叉树C# 实现貌似没有 顺手些了一个
大致思路是:
传入根节点,然后依次循环其子节点推入到栈中,
当推入的节点没有子节点的时候(叶子)或者所有子节点均已经遍历过后(上一次遍历的节点是该节点的右子节点),再依次退出栈。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication5 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Node treeRoot = CreateTree(); 14 scanTree(treeRoot); 15 } 16 17 private static void scanTree(Node treeRoot) 18 { 19 List<Node> list = new List<Node>(); 20 list.Add(treeRoot); 21 Node point = treeRoot; 22 Write(treeRoot); 23 while (true) 24 { 25 if (!list.Contains(point)) 26 { //上一轮是移除的操作 27 if (treeRoot.leftSon == point) 28 {//移除的是左结点 29 if (treeRoot.rightSon != null) 30 { 31 treeRoot = treeRoot.rightSon; 32 list.Add(treeRoot); 33 Write(treeRoot); 34 point = treeRoot; 35 continue; 36 } 37 list.Remove(treeRoot); 38 if (list.Count == 0) 39 { 40 break; 41 } 42 point = treeRoot; 43 treeRoot = list[list.Count - 1]; 44 } 45 else 46 {//移除的是右结点 47 list.Remove(treeRoot); 48 if (list.Count == 0) 49 { 50 break; 51 } 52 point = treeRoot; 53 treeRoot = list[list.Count - 1]; 54 } 55 continue; 56 } 57 58 if (treeRoot.leftSon != null) 59 { 60 treeRoot = treeRoot.leftSon; 61 Write(treeRoot); 62 list.Add(treeRoot); 63 point = treeRoot; 64 continue; 65 } 66 if (treeRoot.rightSon != null) 67 { 68 treeRoot = treeRoot.rightSon; 69 Write(treeRoot); 70 point = treeRoot; 71 list.Add(treeRoot); 72 continue; 73 } 74 //当前的节点是叶子节点 if (treeRoot.leftSon == null && treeRoot.rightSon == null) 75 //{ 76 list.Remove(treeRoot); 77 if (list.Count == 0) 78 { 79 break; 80 } 81 point = treeRoot; 82 treeRoot = list[list.Count - 1]; 83 // } 84 } 85 86 } 87 88 public static void Write(Node node) 89 { 90 Console.WriteLine(node.Data); 91 } 92 93 private static Node CreateTree() 94 { 95 Node a = new Node("A"); 96 a.leftSon = new Node("B"); 97 a.rightSon = new Node("C"); 98 99 a.leftSon.leftSon = new Node("D"); 100 a.leftSon.rightSon = new Node("E"); 101 102 a.rightSon.leftSon = new Node("F"); 103 a.rightSon.rightSon = new Node("G"); 104 105 a.leftSon.leftSon.leftSon = new Node("H"); 106 a.leftSon.leftSon.rightSon = new Node("I"); 107 return a; 108 } 109 } 110 111 class Node 112 { 113 public string Data { get; set; } 114 public Node leftSon { get; set; } 115 public Node rightSon { get; set; } 116 117 public Node(string data) 118 { 119 Data = data; 120 } 121 } 122 }
如果你觉得写的不错,欢迎转载和点赞。 转载时请保留作者署名jilodream/王若伊_恩赐解脱(博客链接:http://www.cnblogs.com/jilodream/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)