树形数据结构初步
# 前言
虽然本蒟蒻通过了PJ训练场的树形数据结构的三道题目,但是感觉每道题都做的十分勉强,所以来补一发树形数据结构的学习。
第一节 树的初步
树的存储
树的定义及基本概念麻烦左转别的算法书籍,本章主要说明树的存储和遍历。
方法一:用数组
const int m=10 struct node{ int data,parent; }tree[m];
方法二:运用树型单链表结构
const int m=10; typedef struct node; typedef node *tree; struct node{ char data; tree child[m]; }; tree t;
方法三:运用树形双链表结构(最推荐的存储方式)
const int m=10; typedef struct node; typedef node *tree; struct node{ char data; tree child[m]; tree father; }; tree t;
树的遍历
ps:本章采用方法三存储树
对于一个普通树(如上图) 有三种遍历的方法
1.先序遍历
先访问根节点,然后按照从左到右的顺序遍历根结点。如上图遍历的顺序就是125634789
遍历方法的伪代码
void firstergodic(tree t,int m){ if(t){ //如果子树非空(既这个点非叶节点) printf("%d",&t.data); for(int i=1;i<=m;++i) tralergodic(t.data,m); } }
2.后序遍历
先从左到右遍历子树,再遍历根结点的顺序,上图的树的后序遍历为562389741
遍历方法的伪代码
const int n=100; int head,tail,i; tree q[n]; tree p; void work(){ tail=head=l; q[tail]=t; tail++; while(head<tail){ p=q[head]; head++; printf("%d",p.data); for(int i=1;i<=m;++i) if(p.data){ q[tail]=p.child[i]; tail++; } } }
第二节 二叉树
二叉树的几点性质
【性质1】在二叉树的第i层上最多有(2^(i-1))个结点。
【性质2】深度为k的二叉树至少有(2^k-1)个结点。
【性质3】对于任意的二叉树,度为2的点比度为0的点多1。
【性质4】(最重要的一点) 对于一棵有n个节点的完全二叉树,对于任意的结点i:
如果i=1,则i节点为根(废话)
如果2*i>n,则节点i为叶结点,否则右儿子编号为2*i
如果2*i+1>n,则结点i无右儿子,否则,右儿子编号为2*i+1
二叉树存储
双儿子法
const int m=11; struct tree{ int data; tree lchild,rchild; }; tree t;
二叉树遍历
先序遍历伪代码
void preorder(tree bt){ if(bt){ //如果树非空 printf("%d",bt.data); preorder(bt.lchild); preorder(bt.rchild); } }
中序遍历伪代码
//中序遍历 void preorder(tree bt){ if(bt){ //如果树非空 preorder(bt.lchild); printf("%d",bt.data); preorder(bt.rchild); } }
后序遍历伪代码
//后序遍历 void preorder(tree bt){ if(bt){ //如果树非空 preorder(bt.lchild); preorder(bt.rchild); printf("%d",bt.data); }
}
以上就是简单树形结构的学习整合,求大佬dd