ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

二叉树

2022-06-24 01:00:28  阅读:143  来源: 互联网

标签:Lchild return int BinaryTree 二叉树 Rchild NULL


 

#include <iostream>
using namespace std;
struct BinaryTree
{
    string data;
    BinaryTree *Lchild;
    BinaryTree *Rchild;
};
void creat(BinaryTree *&T, string k) //先序遍历顺序建立二叉链表
{
    string ch;
    cin >> ch;
    if (ch == k)
        T = NULL;
    else
    {
        T = new BinaryTree;
        T->data = ch;
        creat(T->Lchild, k);
        creat(T->Rchild, k);
    }
}
int m1 = 0,m2=0,m3=0;
void PerOrder(BinaryTree *T) //先序遍历(递归)
{
    if (T)
    {
        if (m1 == 1)
            cout << ',';
        cout << T->data;
        m1 = 1;
        PerOrder(T->Lchild);
        PerOrder(T->Rchild);
    }
    else return;
}
void InOrder(BinaryTree *T) //中序遍历(递归)
{
    if (T)
    {
        InOrder(T->Lchild);
        if (m2 == 1)
            cout << ',';
        cout << T->data;
        m2 = 1;
        InOrder(T->Rchild);
    }
    else return;
}
void PostOrder(BinaryTree *T) //后序遍历(递归)
{
    if (T)
    {
        PostOrder(T->Lchild);
        PostOrder(T->Rchild);
        if (m3 == 1)
            cout << ',';
        cout << T->data;
        m3 = 1;
    }
}
int Depth(BinaryTree *T)//求二叉树深度
{
    int m,n;
    if(T)
    {
        m=Depth(T->Lchild); //递归计算左子树深度为m
        n=Depth(T->Rchild); //递归计算右子树深度为n
        return m>n? m+1 : n+1;
    }
    else return 0;
}
int Depthx(BinaryTree *T,string x)//求二叉树中以值为x的结点为根的子树深度
{
    int m,n;
    if(T)
    {
        if(T->data==x)
          return Depth(T);
        else
        {
            m=Depthx(T->Lchild,x);
            n=Depthx(T->Rchild,x);
            return m>n ? m:n;
        }
    }
    else return 0;
}
int CountLeaf(BinaryTree *T, int &count) //二叉树叶子结点个数
{
    if (T != NULL && T->Lchild == NULL && T->Rchild == NULL) {
        count++;
    }
    if (T != NULL) {
        CountLeaf(T->Lchild, count);
        CountLeaf(T->Rchild, count);
    }
    return count;
}
void change(BinaryTree *T)//交换左右子树(所有)
{
    if(T==NULL) return ;
    else {
        BinaryTree *p=T->Lchild;
        T->Lchild=T->Rchild;
        T->Rchild=p;
        change(T->Lchild);
        change(T->Rchild);
    }
}
void DestroyTree(BinaryTree *T)
{
    if(T==NULL) return;
    DestroyTree(T->Lchild);
    DestroyTree(T->Rchild);
    free(T);
}
int main()
{
    BinaryTree *Tree;
    string k;
    cin >> k;
    creat(Tree, k);//创建


    //需要什么加什么
    
    return 0;
}

 

标签:Lchild,return,int,BinaryTree,二叉树,Rchild,NULL
来源: https://www.cnblogs.com/asterism070/p/16407320.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有