二叉树的定义与前序、中序、后序遍历
二叉树定义(递归方式):
class Node { public int Key; public Node Left, Right; public Node(int item) { Key = item; Left = Right = null; } } class BinaryTree { // Root of Binary Tree public Node Root; public BinaryTree() { Root = null; } /* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ public void printPostorder(Node node) { if (node == null) return; // first recur on left subtree printPostorder(node.Left); // then recur on right subtree printPostorder(node.Right); // now deal with the node Console.WriteLine(node.Key + " "); } /* Given a binary tree, print its nodes in inorder*/ public void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.Left); /* then print the data of node */ Console.WriteLine(node.Key + " "); /* now recur on right child */ printInorder(node.Right); } /* Given a binary tree, print its nodes in preorder*/ public void printPreorder(Node node) { if (node == null) return; /* first print data of node */ Console.WriteLine(node.Key + " "); /* then recur on left sutree */ printPreorder(node.Left); /* now recur on right subtree */ printPreorder(node.Right); } // Wrappers over above recursive functions public void printPostorder() { printPostorder(Root); } public void printInorder() { printInorder(Root); } public void printPreorder() { printPreorder(Root); } }
前、中、后序的遍历:
/** * 二叉树 */ static void Main(string[] args) { /** * 1 * / \ * 2 3 * / \ * 4 5 * **/ BinaryTree tree = new BinaryTree(); tree.Root = new Node(1); tree.Root.Left = new Node(2); tree.Root.Right = new Node(3); tree.Root.Left.Left = new Node(4); tree.Root.Left.Right = new Node(5); Console.WriteLine("Preorder traversal of binary tree is "); tree.printPreorder(); Console.WriteLine("\nInorder traversal of binary tree is "); tree.printInorder(); Console.WriteLine("\nPostorder traversal of binary tree is "); tree.printPostorder(); Console.ReadKey(); }
输出结果:
还有使用非递归的方式实现遍历的方式,以及删除节点等处理请参考:https://blog.csdn.net/sinat_36246371/article/details/53351204
后序再研究,目前记不清。。。。
感谢您的阅读,如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮。本文欢迎各位转载,但是转载文章之后必须在文章页面中给出作者和原文连接。
基础才是编程人员应该深入研究的问题,比如:
1)List/Set/Map内部组成原理|区别
2)mysql索引存储结构&如何调优/b-tree特点、计算复杂度及影响复杂度的因素。。。
3)JVM运行组成与原理及调优
4)Java类加载器运行原理
5)Java中GC过程原理|使用的回收算法原理
6)Redis中hash一致性实现及与hash其他区别
7)Java多线程、线程池开发、管理Lock与Synchroined区别
8)Spring IOC/AOP 原理;加载过程的。。。
【+加关注】。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· 本地部署 DeepSeek:小白也能轻松搞定!
· 基于DeepSeek R1 满血版大模型的个人知识库,回答都源自对你专属文件的深度学习。
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 大人,时代变了! 赶快把自有业务的本地AI“模型”训练起来!
· Tinyfox 简易教程-1:Hello World!