typedef char TElemType
typedef struct BiTNode /*结点定义*/
{
TElemType data
struct BiTNode *lchild
struct BiTNode *rchild
}BiTNode,*BiTree
BiTNode *CreateBiTree()
{
char c
BiTNode *Root
scanf("%c",&c)
if(c=='@') Root=NULL
else{
Root=(BiTNode *)malloc(sizeof(BiTNode))
Root->data=c
Root->lchild=CreateBiTree()
Root->rchild=CreateBiTree()
}
return(Root)
}
void PrintTree(BiTree T,int h)
{
int i
if (T){
PrintTree(T->rchild,h+1)
for(i=0i<hi++) printf(" ")
printf("%c\n",T->data)
PrintTree(T->lchild,h+1)
}
}
main( )
{
BiTNode* Root
Root=CreateBiTree()
PrintTree(Root,0)
return 0
}
您好,想要实现一个二叉树,需要用到结构体来存储每个节点的信息,并使用指针来存储每个节点的左右子节点的地址。具体的实现方法可以参考下面的代码示例:
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val
struct TreeNode *left
struct TreeNode *right
}
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*) malloc(sizeof(struct TreeNode))
node->val = val
node->left = NULL
node->right = NULL
return node
}
void insertNode(struct TreeNode* root, int val) {
if (root == NULL) {
return
}
if (val <root->val) {
if (root->left == NULL) {
root->left = createNode(val)
} else {
insertNode(root->left, val)
}
} else {
if (root->right == NULL) {
root->right = createNode(val)
} else {
insertNode(root->right, val)
}
}
}
void printTree(struct TreeNode* root) {
if (root == NULL) {
return
}
printf("%d\n", root->val)
printTree(root->left)
printTree(root->right)
}
int main() {
struct TreeNode* root = createNode(5)
insertNode(root, 3)
insertNode(root, 2)
insertNode(root, 4)
insertNode(root, 7)
insertNode(root, 6)
insertNode(root, 8)
printTree(root)
return 0
}
在这段代码中,我们定义了一个结构体 TreeNode 来表示二叉树的每个节点,结构体中包含了一个节点的数值 val,以及指向左子节点和右子节点的指针 left 和 right。
以下代码可实现二叉树的递归创建与中序遍历,但在输入时需在输入完有效数据后再连续输入多个负数才可以。#include <stdio.h>
#include <stdlib.h>
typedef struct BitNode
{
int data
struct BitNode *lchile,*rchild
}*BiTree
BiTree CreateBiTree(BiTree &T)
{
int d
scanf("%d",&d)
if (d<0)
return NULL
else
{
if (!(T=(BiTree)malloc(sizeof(BiTree))))
{
exit(1)
}
T->data=d//先根序创建二叉树
printf("%d ",T->data)
T->lchile=CreateBiTree(T->lchile)//创建左子树
T->rchild=CreateBiTree(T->rchild)//创建右子树
return T
}
}
void InOrderView(BiTree &T)//中序遍历二叉树
{
if(T)
{
InOrderView(T->lchile)
printf("%d ",T->data)
InOrderView(T->rchild)
}
}
void main()
{
BiTree T
T=CreateBiTree(T)//递归创建二叉树
InOrderView(T)
}