二叉树创建和遍历 C++

描述

题目描述
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
输入描述:
输入包括1行字符串,长度不超过100。
输出描述:
可能有多组测试数据,对于每组数据,
输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。
每个输出结果占一行。

示例1

输入
abc##de#g##f###
输出
c b e g d f a

分析

就是根据前序字符串建立二叉树,然后再中序遍历。关键在建立,新建树的BitNode类型,然后递归建树

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
char tree[105];
using namespace std;
typedef struct node {
    char data;
    struct node * lchild;
    struct node * rchild;
}BitNode;
int len = 0;
int pos = 0;
BitNode* createTree()
{
    if (pos >= strlen(tree))return NULL;
    if (tree[pos] == '#') { pos++; return NULL; }
    else {
        BitNode * T = new BitNode;
        T->data= tree[pos++];
        T->lchild = createTree();
        T->rchild = createTree();
        return T;
    }
}
void Inorder(BitNode*T)
{
    if (T != NULL)
    {
        Inorder(T->lchild);
        cout << T->data<<" ";
        Inorder(T->rchild);
    }
}
int main()
{
    while (~scanf("%s", tree))
    {
        pos = 0;
        BitNode * T = createTree();
        Inorder(T);
        cout << "\n";
    }
}

补充

前序遍历:

void PreOrder(BitNode * T)
{
  if(T!=NULL){
cout<<T->data<<" ";
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}

后序遍历

void PostOrder(BitNode * T)
{
 if(T!=NULL){
  PostOrder(T->lchild);
  PostOrder(T->rchild);
  cout<<T->data<<" ";
}
}

以广义表的形式输出二叉树:

void printBinTree(BitNode * T){
 if(T!=NULL)
 {
  cout<<T->data;
  if(T->lchild!=NULL || T->rchild!=NULL)
  {  cout<<'(';
      printBinTree(T->lchild);
      cout<<',';
      if(T->rchild!=NULL)printBinTree(T->rchild);
      cout<<')';
   }
}
}

计算一颗二叉树的高度

int Height(BitNode * T)
{
 if(T==NULL) return 0;
  else{
  int i = Height(T->lchild);
  int j = Height(T->rchild);
  if(i<j)return j+1;
  else return i+1
}
}

一些性质:
1、二叉树的第i层,最多有2^i-1个结点
2、深度为k的二叉树最少有k个结点,最多有2^k-1个结点
3、具有n个结点的完全二叉树的深度为log2(n+1)
4、结点i所在层次为log2i+1

猜你喜欢

转载自blog.csdn.net/BeforeEasy/article/details/81736629