二叉树带节点数输出
给出二叉树的先序遍历输出(空结点用’.’)表示,请构造二叉树,并输出二叉树的广义表表示,此广义表中每个结点均带有一个整数,这个整数表示对应的子树上结点总数。
输入说明:
一行仅由‘.’与大小写字符构成的字符串,该字符串表示二叉树的前序遍历输出,其中’.’表示空结点,字符串长度不超过100。
输出说明:
在单独一行中二叉树的广义表表示,此广义表中每个结点均带有一个整数,这个整数表示对应的子树上结点总数。具体格式参考输出样例。
输入样列:
ABD…C..
输出样列:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
#include <cctype>
using namespace std;
#define N 100
typedef char Element;
struct Node
{
Element data;
int num;
struct Node *lchild;
struct Node *rchild;
};
typedef struct Node BTNode;
typedef struct Node * BTree;
BTree Create_BTree();
BTree NewNode(Element x);
void PrintBTreeNum(BTree root);
void Pre_Order(BTree root);
int GetNum(BTree root);
int main()
{
BTree root;
root=Create_BTree();
Pre_Order(root);
PrintBTreeNum(root);
printf("\n");
return 0;
}
BTree NewNode(Element x)
{
BTree p=(BTree)malloc(sizeof(BTNode));
p‐>data=x;
p‐>lchild=NULL;
p‐>rchild=NULL;
return p;
}
BTree Create_BTree()
{
BTree root;
char c;
c=getchar();
if(c=='.')
return NULL;
root=NewNode(c);
root‐>lchild=Create_BTree();
root‐>rchild=Create_BTree();
return root;
}
void Pre_Order(BTree root)
{
if(root!=NULL)
{
root‐>num=GetNum(root);
Pre_Order(root‐>lchild);
Pre_Order(root‐>rchild);
}
}
int GetNum(BTree root)
{
int num;
if(root==NULL)
return 0;
num=1;
if(root‐>lchild!=NULL)
num+=GetNum(root‐>lchild);
if(root‐>rchild!=NULL)
num+=GetNum(root‐>rchild);
return num;
}
void PrintBTreeNum(BTree root)
{
if(root==NULL);
printf("%c[%d]",root‐>data,root‐>num);
if(root‐>lchild==NULL&&root‐>rchild==NULL);
printf("(");
if(root‐>lchild!=NULL)
PrintBTreeNum(root‐>lchild);
printf(",");
if(root‐>rchild!=NULL)
PrintBTreeNum(root‐>rchild);
printf(")");
}
二叉树树状输出I
给出二叉树的先序遍历输出(空结点用’.’)表示,请构造二叉树,并按树状输出该二叉树(竖向)。
输入说明:
一行仅由‘.’与大小写字符构成的字符串,该字符串表示二叉树的前序遍历输出,其中’.’表示空结点,字符串长度不超过100。
输出说明:
输出有若干行,为二叉树的树状输出(竖向),具体格式参考输出样例,为明显起见