本文实例讲述了C#非递归先序遍历二叉树的方法。分享给大家供大家参考。具体如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceConsoleApplication5 { classProgram { staticvoidMain(string[]args) { NodetreeRoot=CreateTree(); scanTree(treeRoot); } privatestaticvoidscanTree(NodetreeRoot) { List<Node>list=newList<Node>(); list.Add(treeRoot); Nodepoint=treeRoot; Write(treeRoot); while(true) { if(!list.Contains(point)) {//上一轮是移除的操作 if(treeRoot.leftSon==point) {//移除的是左结点 if(treeRoot.rightSon!=null) { treeRoot=treeRoot.rightSon; list.Add(treeRoot); Write(treeRoot); point=treeRoot; continue; } list.Remove(treeRoot); if(list.Count==0) { break; } point=treeRoot; treeRoot=list[list.Count-1]; } else {//移除的是右结点 list.Remove(treeRoot); if(list.Count==0) { break; } point=treeRoot; treeRoot=list[list.Count-1]; } continue; } if(treeRoot.leftSon!=null) { treeRoot=treeRoot.leftSon; Write(treeRoot); list.Add(treeRoot); point=treeRoot; continue; } if(treeRoot.rightSon!=null) { treeRoot=treeRoot.rightSon; Write(treeRoot); point=treeRoot; list.Add(treeRoot); continue; } if(treeRoot.leftSon==null&&treeRoot.rightSon==null) { list.Remove(treeRoot); if(list.Count==0) { break; } point=treeRoot; treeRoot=list[list.Count-1]; } } } publicstaticvoidWrite(Nodenode) { Console.WriteLine(node.Data); } privatestaticNodeCreateTree() { Nodea=newNode("A"); a.leftSon=newNode("B"); a.rightSon=newNode("C"); a.leftSon.leftSon=newNode("D"); a.leftSon.rightSon=newNode("E"); a.rightSon.leftSon=newNode("F"); a.rightSon.rightSon=newNode("G"); a.leftSon.leftSon.leftSon=newNode("H"); a.leftSon.leftSon.rightSon=newNode("I"); returna; } } classNode { publicstringData{get;set;} publicNodeleftSon{get;set;} publicNoderightSon{get;set;} publicNode(stringdata) { Data=data; } } }
希望本文所述对大家的C#程序设计有所帮助。
您可能感兴趣的文章:C++基于先序、中序遍历结果重建二叉树的方法C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法二叉树先根(先序)遍历的改进探讨:C++实现链式二叉树(用非递归方式先序,中序,后序遍历二叉树)通过先序遍历和中序遍历后的序列还原二叉树(实现方法)
C语言动态内存分配的详解
数据结构 红黑树的详解
上述就是C#学习教程:C#非递归先序遍历二叉树实例分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。
如若转载,请注明出处:https://www.ctvol.com/cdevelopment/906687.html