数据结构之树

    科技2022-07-15  126

    **

    ** 树就是一个有n个节点的有限集。树由根节点,子树组成,一个节点可以有多个子树,但一个子树只能由一个父节点。树有顺序存储和链式存储。

    度:节点用户有的子树个数。 树的度:树中各个结点的最大值。

    储存方式:双亲表示法,孩子表示法,孩子兄弟表示法。

    **

    二叉树

    ** 树,每个节点最多有两个子树。二叉树又分为满二叉树和完全二叉树。满二叉树,所有分支节点都有左右子树,并且所有叶节点都在同一层。完全二叉树:假设这个二叉树有h层,除了h层其他层都达到了最大节点数,并且在第h层每个节点都是从左到右连续的。

    二叉树性质: 第i层最多有2的i-1次方个节点 深度为K。最多有2的k次方-1个节点 叶节点为n0,度为2的节点为n2则 n0=n2+1

    完全二叉树 有n个节点那么深度为log2 n次方+1 n个结点 i=0 根节点 i>1 双亲结点 i/2 2i大于n i节点无左孩子 2i+1>n无右孩子

    遍历 先判断是否为空 其中涉及到中序遍历(输出顺序左中右),前序遍历(自己左右),后续遍历(左右自己)。

    每层最多2的i次方-1个节点

    任意一个完全二叉树满足

    该节点 i 右孩子 2i 左孩子2i+1 父亲 2i

    顺序结构一般是完全二叉树

    树类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace tree { class BiTree<T> { private T[] data; private int count; public BiTree(int size) { this.data = new T[size]; this.count = 0; } public bool Add(T item) { if(count>=data.Length) { return false; } data[count] = item; count++; return true; } public void FirstTravelSal() { FirstTravelSal(0); } private void FirstTravelSal(int index) { if(index >= count) { return; } if(data[index].Equals(-1)) { return; } //先输出该节点 int num = index + 1; Console.Write(data[index]+" "); int leftNum = num * 2; int rightNum = num * 2 + 1; //输出左节点 FirstTravelSal(leftNum - 1); //输出右节点 FirstTravelSal(rightNum - 1); } public void MiddleTravelSal() { MiddleTravelSal(0); } private void MiddleTravelSal(int index) { if (index >= count) { return; } if (data[index].Equals(-1)) { return; } int num = index + 1; int leftNum = num * 2; int rightNum = num * 2 + 1; //先输出左节点 MiddleTravelSal(leftNum - 1); //在输出该节点 Console.Write(data[index] + " "); //输出右节点 MiddleTravelSal(rightNum - 1); } public void LastTravelSal() { LastTravelSal(0); } private void LastTravelSal(int index) { if (index >= count) { return; } if (data[index].Equals(-1)) { return; } int num = index + 1; int leftNum = num * 2; int rightNum = num * 2 + 1; LastTravelSal(leftNum - 1); LastTravelSal(rightNum - 1); Console.Write(data[index] + " "); } public void LayerTravelSal() { for(int i =0;i<count;i++) { Console.Write(data[i]+" "); } } } }

    主函数

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace tree { class Program { static void Main(string[] args) { char[] arry = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' }; BiTree<char> tree = new BiTree<char>(10); for(int i=0;i<arry.Length;i++) { tree.Add(arry[i]); } tree.LayerTravelSal(); Console.ReadLine(); } } }
    Processed: 0.016, SQL: 8