数据结构知识整理 - 遍历二叉树的应用

版权声明: https://blog.csdn.net/Ha1f_Awake/article/details/85186275

主要内容


 

建立二叉链表

在先序遍历的递归算法中,将输出语句改为输入语句即可。(可回顾“递归算法”)

需要注意的是,递归算法会遍历满二叉树中的每一个结点,所以我们必须对空结点进行判断和输入。

void CreatBiTree(BiTree &T)
{
    cin>>ch;                    /*按先序序列输入字符*/

    if(ch == '#') T = NULL;     /*输入字符为#,代表结点为空*/

    else
    {
        T->data = ch;        
    
        CreatBitree(T->lchild);    /*递归创建左子树*/

        CreatBitree(T->rchild);    /*递归创建右子树*/
    }
}

复制二叉树

void CopyBiTree(BiTree T, BiTree &NT)
{
    if(T == NULL) NT = NULL;            /*空树(空结点)就没必要复制了*/
    
    else
    {
        NT->data = T->data;
        
        CopyBiTree(T->lchild, NT->lchild);    /*递归复制左子树*/

        CopyBitree(T->rchild, NT->rchild);    /*递归复制右子树*/
    }
}

计算二叉树深度

int Depth(BiTree T)
{
    if(T == NULL) return 0;    /*空树深度为0*/

    else
    {
        int m = Depth(T->lchild);    /*递归计算左子树的深度*/

        int n = Depth(T->rchild);    /*递归计算右子树的深度*/

        int d = (m > n) ? m : n;     /*取左、右子树中更大的深度*/

        return d++;                  /*返回d+1,包括根结点的深度*/
    }
}

统计二叉树的结点个数

int CountBinode(BiTree T)
{
    if(T = NULL) return 0;

    else
    {
        int m = CountBinode(T->lchild);    /*递归计算左子树的结点个数*/

        int n = CountBinode(T->rchild);    /*递归计算右子树的结点个数*/

        return 1 + m + n;                  /*1代表根结点*/
    }
}

猜你喜欢

转载自blog.csdn.net/Ha1f_Awake/article/details/85186275