[cpp] 】
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
struct tnode
{
int data;
struct tnode *lchild;
struct tnode *rchild;
}tnode;
typedef struct tnode * TNode;
//此程序中沒用上
TNode newNode(int data)
{
TNode node = (TNode)malloc(sizeof(struct tnode));
node->data = data;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
TNode createTree(TNode root)
{
int data = 0;
scanf("%d", &data);
if(data == -1) return NULL;
root = (TNode)malloc(sizeof(struct tnode));
root->data = data;
root->lchild = NULL;
root->rchild = NULL;
root->lchild = createTree(root->lchild);//如果不賦值給root->lchild則左子樹不會被創建,root->lchild依然會是NULL
root->rchild = createTree(root->rchild);
return root;
}
void preorderTraverse(TNode root)
{
if(root != NULL)
{
printf("%d ", root->data);
preorderTraverse(root->lchild);
preorderTraverse(root->rchild);
}
}
int treeDepth(TNode root)
{
if(root == NULL)
return 0;
int nleft = treeDepth(root->lchild);
int nright = treeDepth(root->rchild);
return (nleft > nright) ? (nleft + 1) : (nright + 1);
}
void treeFree(TNode root)
{
if(root != NULL)
{
treeFree(root->lchild);
treeFree(root->rchild);
printf("%d ", root->data);
free(root);
}
}
void test()
{
TNode root = NULL;
root = createTree(root);
preorderTraverse(root);
printf("\n");
int depth = treeDepth(root);
printf("depth = %d\n", depth);
treeFree(root);
}
int main()
{
test();
return 0;
}
/*****************************\
1
2 6
-1 5 4 -1
-1 -1 -1 -1
\*****************************/
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
struct tnode
{
int data;
struct tnode *lchild;
struct tnode *rchild;
}tnode;
typedef struct tnode * TNode;
//此程序中沒用上
TNode newNode(int data)
{
TNode node = (TNode)malloc(sizeof(struct tnode));
node->data = data;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
TNode createTree(TNode root)
{
int data = 0;
scanf("%d", &data);
if(data == -1) return NULL;
root = (TNode)malloc(sizeof(struct tnode));
root->data = data;
root->lchild = NULL;
root->rchild = NULL;
root->lchild = createTree(root->lchild);//如果不賦值給root->lchild則左子樹不會被創建,root->lchild依然會是NULL
root->rchild = createTree(root->rchild);
return root;
}
void preorderTraverse(TNode root)
{
if(root != NULL)
{
printf("%d ", root->data);
preorderTraverse(root->lchild);
preorderTraverse(root->rchild);
}
}
int treeDepth(TNode root)
{
if(root == NULL)
return 0;
int nleft = treeDepth(root->lchild);
int nright = treeDepth(root->rchild);
return (nleft > nright) ? (nleft + 1) : (nright + 1);
}
void treeFree(TNode root)
{
if(root != NULL)
{
treeFree(root->lchild);
treeFree(root->rchild);
printf("%d ", root->data);
free(root);
}
}
void test()
{
TNode root = NULL;
root = createTree(root);
preorderTraverse(root);
printf("\n");
int depth = treeDepth(root);
printf("depth = %d\n", depth);
treeFree(root);
}
int main()
{
test();
return 0;
}
/*****************************\
1
2 6
-1 5 4 -1
-1 -1 -1 -1
\*****************************/