C#非递归先序遍历二叉树实例
程序员文章站
2023-11-20 22:32:52
本文实例讲述了c#非递归先序遍历二叉树的方法。分享给大家供大家参考。具体如下:
using system;
using system.collections.g...
本文实例讲述了c#非递归先序遍历二叉树的方法。分享给大家供大家参考。具体如下:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace consoleapplication5 { class program { static void main(string[] args) { node treeroot = createtree(); scantree(treeroot); } private static void scantree(node treeroot) { list<node> list = new list<node>(); list.add(treeroot); node point = 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]; } } } public static void write(node node) { console.writeline(node.data); } private static node createtree() { node a = new node("a"); a.leftson = new node("b"); a.rightson = new node("c"); a.leftson.leftson = new node("d"); a.leftson.rightson = new node("e"); a.rightson.leftson = new node("f"); a.rightson.rightson = new node("g"); a.leftson.leftson.leftson = new node("h"); a.leftson.leftson.rightson = new node("i"); return a; } } class node { public string data { get; set; } public node leftson { get; set; } public node rightson { get; set; } public node(string data) { data = data; } } }
希望本文所述对大家的c#程序设计有所帮助。
上一篇: C#中调用MySQL存储过程的方法