二叉树(1)基本概念以及三种遍历
来源:互联网 发布:机智自动交易软件 编辑:程序博客网 时间:2024/06/05 16:41
1.二叉树的相关概念
二叉树的定义
二叉树(Binary Tree)是n(n>=0)个有限元素的集合,该集合或者为空,或者由一个称为根(root)的元素及两个不相交的,被称为左子树和右子树的二叉树组成。当集合为空时,称该二叉树为空二叉树,在二叉树中,一个元素也称为一个结点。
二叉树是有序的,即若将其左右子树颠倒,就称为另一颗不同的二叉树。
结点的度:结点所拥有的子树的个数称为该结点的度。
叶结点:度为0的结点称为叶结点,或者称为终端结点。
树的深度:树中所有结点的最大层数称为树的深度。
树的度:树中个结点度的最大值称为该树的度。
2.二叉树的三种遍历方式
二叉树有三种遍历方式:前序(父节点,左节点,右节点),中序(左节点,父节点,右节点),后序(左节点,右节点,父节点)。
如上图所示的一颗二叉树,按照三种遍历方式所打印的结果应该是:
前序:1 2 4 8 9 5 10 11 3 6 7
中序:8 4 9 2 10 5 11 1 6 3 7
后序:8 9 4 10 11 5 2 6 7 3 1
代码:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace binaryTree{ class Program { static void Main(string[] args) { BTree tree = new BTree(3); BTreeNode temp5 = new BTreeNode(5); tree.GetHead().lChild = temp5; BTreeNode temp7 = new BTreeNode(7); tree.GetHead().rChild = temp7; BTreeNode temp1 = new BTreeNode(1); temp5.lChild = temp1; BTreeNode temp2 = new BTreeNode(2); temp5.rChild = temp2; BTreeNode temp4 = new BTreeNode(4); temp7.lChild = temp4; BTreeNode temp6 = new BTreeNode(6); temp7.rChild = temp6; BTreeNode temp9 = new BTreeNode(9); temp1.lChild = temp9; tree.inorderTraverse(); } } class BTreeNode { public int data; public BTreeNode lChild; public BTreeNode rChild; //构造函数 public BTreeNode(int x) { data = x; } } class BTree { private BTreeNode head; public BTreeNode GetHead() { return head; } public BTree(int x) { head = new BTreeNode(x); } //前序遍历 public void preorderTraverse(BTreeNode head) { if (head == null) { Console.WriteLine("empty binary Tree!"); return; } Console.WriteLine(head.data); if (head.lChild!=null) preorderTraverse(head.lChild); if (head.rChild!=null) preorderTraverse(head.rChild); } //中序遍历 public void inorderTraverse(BTreeNode node=null) { if (node == null) node = head; if (node == null) Console.WriteLine("empty tree"); if (node.lChild != null) inorderTraverse(node.lChild); Console.WriteLine(node.data); if (node.rChild != null) inorderTraverse(node.rChild); } }}
0 0
- 二叉树(1)基本概念以及三种遍历
- 树和二叉树基本概念以及二叉树遍历
- java实现二叉树的构建以及三种遍历方法(先序遍历,中序遍历,后续遍历)
- 二叉树(一):二叉树的创建以及三种遍历方法的递归实现
- [树]二叉树的建立以及三种遍历
- Java构造二叉树以及三种递归遍历
- 二叉树的建立以及三种遍历方式
- Java实现二叉树建立以及三种遍历
- C++编程练习(8)----“二叉树的建立以及二叉树的三种遍历方式“(前序遍历、中序遍历、后续遍历)
- 数据结构之二叉树 (构造 拷贝构造 以及前序中序后续三种遍历方法)
- C语言基本数据结构之二(二叉树的三种遍历,节点数以及深度算法)
- 创建二叉树的两种方法以及三种遍历方法
- Java实现完全二叉树的构建以及三种遍历方式
- 二叉树的存储方式以及递归和非递归的三种遍历方式
- Java实现二叉树的建立以及三种递归遍历
- (学习java)二叉树的链式实现以及三种遍历方式
- 二叉树的三种遍历(递归)
- 二叉树的三种遍历(递归+非递归)
- 用Lazarus编写第一个程序Pascal版的hello world
- Linux -- uname命令查询操作系统
- OSX 修改环境变量
- MingW Cmake bulid OpenCV
- android MediaCodec 音频编解码的实现——转码
- 二叉树(1)基本概念以及三种遍历
- 关于象棋最短路径的一个问题
- JDK 1.7 Integer.parseInt 源码解析
- 引用(三)
- python的注释
- Android开发如何进阶?
- play with framework
- HDU 1256 画8
- 关于HashMap 中的 transient table