C#實現二叉樹的前序、中序、后序遍歷。
站在用戶的角度思考問題,與客戶深入溝通,找到靈武網站設計與靈武網站推廣的解決方案,憑借多年的經驗,讓設計與互聯網技術結合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:網站設計制作、網站制作、企業(yè)官網、英文網站、手機端網站、網站推廣、申請域名、網絡空間、企業(yè)郵箱。業(yè)務覆蓋靈武地區(qū)。
public class BinaryTreeNode { int value; BinaryTreeNode left; BinaryTreeNode right; ////// 前序遍歷 /// /// public static void PreOrder(BinaryTreeNode tree) { if (tree == null) return; System.Console.Write(tree.value + " "); PreOrder(tree.left); PreOrder(tree.right); } ////// 前序遍歷循環(huán)實現 /// /// public static void PreOrderLoop(BinaryTreeNode tree) { if (tree == null) return; Stackstack = new Stack (); BinaryTreeNode node = tree; while(node != null || stack.Any()){ if(node != null) { stack.Push(node); System.Console.Write(node.value + " "); node = node.left; } else { var item = stack.Pop(); node = item.right; } } } /// /// 中序遍歷 /// /// public static void InOrder(BinaryTreeNode tree) { if (tree == null) return; InOrder(tree.left); System.Console.Write(tree.value + " "); InOrder(tree.right); } ////// 中序遍歷循環(huán)實現 /// /// public static void InOrderLoop(BinaryTreeNode tree) { if (tree == null) return; Stackstack = new Stack (); BinaryTreeNode node = tree; while (node != null || stack.Any()) { if (node != null) { stack.Push(node); node = node.left; } else { var item = stack.Pop(); System.Console.Write(item.value + " "); node = item.right; } } } /// /// 后序遍歷 /// /// public static void PostOrder(BinaryTreeNode tree) { if (tree == null) return; PostOrder(tree.left); PostOrder(tree.right); System.Console.Write(tree.value + " "); } ////// 后序遍歷循環(huán)實現1 /// /// public static void PostOrderLoop(BinaryTreeNode tree) { if (tree == null) return; Stackstack = new Stack (); BinaryTreeNode node = tree; BinaryTreeNode pre = null; stack.Push(node); while (stack.Any()) { node = stack.Peek(); if ((node.left == null && node.right == null) || (pre != null && (pre == node.left || pre == node.right))) { System.Console.Write(node.value + " "); pre = node; stack.Pop(); } else { if (node.right != null) stack.Push(node.right); if (node.left != null) stack.Push(node.left); } } } /// /// 后續(xù)遍歷循環(huán)實現2 /// /// public static void PostOrderLoop2(BinaryTreeNode tree) { HashSetvisited = new HashSet (); Stack stack = new Stack (); BinaryTreeNode node = tree; while (node != null || stack.Any()) { if (node != null) { stack.Push(node); node = node.left; } else { var item = stack.Peek(); if (item.right != null && !visited.Contains(item.right)) { node = item.right; } else { System.Console.Write(item.value + " "); visited.Add(item); stack.Pop(); } } } } }