C#实现二叉树的各种遍历
1. 引言
在实际的项目中,树还是用的比较多的一种,尤其是对于具有层次结构的数据。相信很多人都学过树的遍历,比如先序遍历,后序遍历等,利用递归还是很容易理解的。
今天给大家介绍下二叉树的几种遍历算法,包括递归和非递归的实现。
首先建立一棵二叉树 如:
[DebuggerDisplay("Value={Value}")]
public class Tree
{
public string Value;
public Tree Left;
public Tree Right;
} public static Tree CreatFakeTree()
{
Tree tree = new Tree() {Value = "A"};
tree.Left = new Tree()
{
Value = "B",
Left = new Tree() {Value = "D", Left = new Tree() {Value = "G"}},
Right = new Tree() {Value = "E", Right = new Tree() {Value = "H"}}
};
tree.Right = new Tree() {Value = "C", Right = new Tree() {Value = "F"}}; return tree;
}
一棵简单的二叉树
2. 先序遍历
先序遍历还是很好理解的,一次遍历根节点,左子树,右子数
递归实现
public static void PreOrder(Tree tree)
{
if (tree == null)
return; System.Console.WriteLine(tree.Value);
PreOrder(tree.Left);
PreOrder(tree.Right);
}
非递归实现
public static void PreOrderNoRecursion(Tree tree)
{
if(tree == null)
return; System.Collections.Generic.Stack<Tree> stack = new System.Collections.Generic.Stack<Tree>();
Tree node = tree; while (node != null || stack.Any())
{
if (node != null)
{
stack.Push(node);
System.Console.WriteLine(node.Value);
node = node.Left;
}
else
{
var item = stack.Pop();
node = item.Right;
}
}
}
输出结果:
3. 中序遍历
递归实现
public static void InOrder(Tree tree)
{
if(tree == null)
return; InOrder(tree.Left);
System.Console.WriteLine(tree.Value);
InOrder(tree.Right);
}
非递归实现
public static void InOrderNoRecursion(Tree tree)
{
if (tree == null)
return; System.Collections.Generic.Stack<Tree> stack = new System.Collections.Generic.Stack<Tree>();
Tree node = tree; while (node != null || stack.Any())
{
if (node != null)
{
stack.Push(node);
node = node.Left;
}
else
{
var item = stack.Pop();
System.Console.WriteLine(item.Value); node = item.Right;
}
}
}
输出结果:
4. 后序遍历
递归实现
public static void PostOrder(Tree tree)
{
if (tree == null)
return; PostOrder(tree.Left);
PostOrder(tree.Right);
System.Console.WriteLine(tree.Value);
}
非递归实现 比前两种稍微复杂一点。要保证左右节点都被访问后,才能访问根节点。这里给出两种形式。
public static void PostOrderNoRecursion(Tree tree)
{
if (tree == null)
return; System.Collections.Generic.Stack<Tree> stack = new System.Collections.Generic.Stack<Tree>();
Tree node = tree;
Tree 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.WriteLine(node.Value);
pre = node; stack.Pop();
}
else
{
if(node.Right != null)
stack.Push(node.Right); if(node.Left != null)
stack.Push(node.Left);
}
}
} public static void PostOrderNoRecursion2(Tree tree)
{
HashSet<Tree> visited = new HashSet<Tree>();
System.Collections.Generic.Stack<Tree> stack = new System.Collections.Generic.Stack<Tree>();
Tree 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.WriteLine(item.Value);
visited.Add(item);
stack.Pop();
}
}
}
}
输出结果:
5. 层序遍历
层序遍历就是按照层次由左向右输出
public static void LevelOrder(Tree tree)
{
if(tree == null)
return; Queue<Tree> queue = new Queue<Tree>();
queue.Enqueue(tree); while (queue.Any())
{
var item = queue.Dequeue();
System.Console.Write(item.Value); if (item.Left != null)
{
queue.Enqueue(item.Left);
} if (item.Right != null)
{
queue.Enqueue(item.Right);
}
}
}
输出结果:
6. Z-型层序遍历
Z-层序遍历就是奇数层按照由左向右输出,偶数层按照由右向左输出,这里定义了几个辅助函数,比如计算节点所在的层次。算法思想是按照层次保存树形节点,应该是有更加优化的算法,希望大家指出。
public static int GetDepth(Tree tree, Tree node)
{
if (tree == null)
return ; if (tree == node)
return ; if (tree.Left == node || tree.Right == node)
return ; int lDepth = GetDepth(tree.Left, node);
lDepth = lDepth == ? : lDepth + ; int rDepth = GetDepth(tree.Right, node);
rDepth = rDepth == ? : rDepth + ; return lDepth >= rDepth ? lDepth : rDepth;
} public static void Z_LevelOrder(Tree tree, Dictionary<int, List<Tree>> dictionary)
{
if (tree == null)
return; Queue<Tree> queue = new Queue<Tree>();
queue.Enqueue(tree); while (queue.Any())
{
var item = queue.Dequeue();
var depth = GetDepth(tree, item); List<Tree> list;
if (!dictionary.TryGetValue(depth, out list))
{
list = new List<Tree>();
dictionary.Add(depth, list);
}
list.Add(item); if (item.Left != null)
{
queue.Enqueue(item.Left);
} if (item.Right != null)
{
queue.Enqueue(item.Right);
}
}
} public static void Z_LevelOrder(Tree tree)
{
if (tree == null)
return; Dictionary<int, List<Tree>> dictionary = new Dictionary<int, List<Tree>>();
Z_LevelOrder(tree, dictionary); foreach (KeyValuePair<int, List<Tree>> pair in dictionary)
{
if (pair.Key% == )
{
pair.Value.Reverse();
} pair.Value.ForEach(t=> { System.Console.Write(t.Value); });
}
}
输出结果:
C#实现二叉树的各种遍历的更多相关文章
- 二叉树的层序遍历 BFS
二叉树的层序遍历,或者说是宽度优先便利,是经常考察的内容. 问题一:层序遍历二叉树并输出,直接输出结果即可,输出格式为一行. #include <iostream> #include &l ...
- codevs3143 二叉树的序遍历
难度等级:白银 3143 二叉树的序遍历 题目描述 Description 求一棵二叉树的前序遍历,中序遍历和后序遍历 输入描述 Input Description 第一行一个整数n,表示这棵树的节点 ...
- codevs 3143 二叉树的序遍历
传送门 Description 求一棵二叉树的前序遍历,中序遍历和后序遍历 Input 第一行一个整数n,表示这棵树的节点个数. 接下来n行每行2个整数L和R.第i行的两个整数Li和Ri代表编号为i的 ...
- lintcode : 二叉树的层次遍历II
题目 二叉树的层次遍历 II 给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历) 样例 给出一棵二叉树 {3,9,20,#,#,15,7}, ...
- lintcode : 二叉树的层次遍历
题目 二叉树的层次遍历 给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问) 样例 给一棵二叉树 {3,9,20,#,#,15,7} : 3 / \ 9 20 / \ 15 7 返回他的分层遍历 ...
- lintcode :Binary Tree Preorder Traversal 二叉树的前序遍历
题目: 二叉树的前序遍历 给出一棵二叉树,返回其节点值的前序遍历. 样例 给出一棵二叉树 {1,#,2,3}, 1 \ 2 / 3 返回 [1,2,3]. 挑战 你能使用非递归实现么? 解题: 通过递 ...
- Leetcode 102. Binary Tree Level Order Traversal(二叉树的层序遍历)
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...
- 二叉树中序遍历 (C语言实现)
在计算机科学中,树是一种重要的非线性数据结构,直观地看,它是数据元素(在树中称为结点)按分支关系组织起来的结构.二叉树是每个节点最多有两个子树的有序树.通常子树被称作“左子树”(left subtre ...
- 94 Binary Tree Inorder Traversal(二叉树中序遍历Medium)
题目意思:二叉树中序遍历,结果存在vector<int>中 解题思路:迭代 迭代实现: /** * Definition for a binary tree node. * struct ...
- 144 Binary Tree Preorder Traversal(二叉树先序遍历Medium)
题目意思:二叉树先序遍历,结果存在vector<int>中 解题思路:1.递归(题目中说用递归做没什么意义,我也就贴贴代码吧) 2.迭代 迭代实现: class Solution { pu ...
随机推荐
- sublime 3 快捷键
来自(http://dengo.org/archives/970) Sublime text 3是我最喜欢的代码编辑器,每天和代码打交道,必先利其器,掌握基本的代码编辑器的快捷键,能让你打码更有效率. ...
- AngularJS快速入门指南19:示例代码
本文给出的大部分示例都可以直接运行,通过点击运行按钮来查看结果,同时支持在线编辑代码. <div ng-app=""> <p>Name: <input ...
- JMS确认机制
JMS中为数不多的重点就是消息的确认机制,下面分别介绍J2EE和Spring的MessageListenerContainer的确认机制 J2EE中JMS确认机制 在JMS规范中一共4种确认方式 AU ...
- String的length()和Array的length
String是个final修饰的最终类,不能被继承,String中属性都设置为private,方法为public,并不提供set方法,想要获得字符串的长度必须调用length()方法这个长度是确定的, ...
- [常见问题]解决创建servlet 找不到webservlet包.
今天在创建一个springmvc项目的时候发现 使用的HttpServletRequest不起作用, 提示需要映入 jar文件, 于是便有了今天的这个问题: 百度了下才发现 项目需要导入Runtime ...
- C#并行编程-Parallel
菜鸟学习并行编程,参考<C#并行编程高级教程.PDF>,如有错误,欢迎指正. 目录 C#并行编程-相关概念 C#并行编程-Parallel C#并行编程-Task C#并行编程-并发集合 ...
- 创建Cookie,简单模拟登录,记录登录名,购物车记录先前添加内容,session控制登录
工作任务:模拟淘宝登录和购物车功能:使用cookie记录登录名,下次登录时能够记得上次的登录名,使用cookie模拟购物车功能,使用session记住登录信息并验证是否登录,防止利用url打开网站, ...
- salesforce 零基础开发入门学习(二)变量基础知识,集合,表达式,流程控制语句
salesforce如果简单的说可以大概分成两个部分:Apex,VisualForce Page. 其中Apex语言和java很多的语法类似,今天总结的是一些简单的Apex的变量等知识. 有如下几种常 ...
- Python数据类型之“数字(numerics)”
上一节内容说的是"Python基本语法",本节主要讲下Python中的数据类型. 存储在内存中的数据通常有两个属性: 在内存中的存放位置:这个存放位置通过变量名可以找到: 在内存中 ...
- 锁&锁与指令原子操作的关系 & cas_Queue
锁 锁以及信号量对大部分人来说都是非常熟悉的,特别是常用的mutex.锁有很多种,互斥锁,自旋锁,读写锁,顺序锁,等等,这里就只介绍常见到的, 互斥锁 这个是最常用的,win32:CreateMute ...