C#非递归先序遍历二叉树实例
本文实例讲述了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#程序设计有所帮助。