二叉树是每个节点最多有两个子树的层次结构,现要求实现函数,判断是否为二叉树
函数接口定义:
int isTree(TreeNode Head);
Head
为要判断的树的头节点,返回1则代表为二叉树,返回0则代表不为二叉树
其中,TreeNode
的结构如下
typedef int ElemType;
typedef struct Node {
ElemType data;
struct Node *lchild, *rchild;
} *TreeNode;
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct Node {
ElemType data;
struct Node *lchild, *rchild;
} *TreeNode;
TreeNode Create();/* 细节在此不表 */
int isTree(TreeNode Head);
int main() {
TreeNode Head;
Head = Create();
if (isTree(Head)) {
printf("YES\n");
} else {
printf("NO\n");
}
Head = Create();
if (isTree(Head)) {
printf("YES\n");
} else {
printf("NO\n");
}
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
第一行为n,代表有n个节点
接下来n行,每行三个数字,代表num
,l
,r
,代表节点num
的左右子孩子为l
和r
题目保证节点数据只有整数,无负数和0
7
1 2 0
2 0 3
3 4 0
4 0 5
5 6 0
6 2 7
7 0 0
7
1 2 0
2 0 3
3 4 0
4 0 5
5 6 0
6 0 7
7 0 0
输出样例:
NO
YES
int isTree(TreeNode Head) {
if(Head==NULL) return 1;
if(Head->lchild!=NULL) {
if(Head->lchild->data<Head->data) return 0;
}
if(Head->rchild!=NULL) {
if(Head->rchild->data<Head->data) return 0;
}
return isTree(Head->lchild)*isTree(Head->rchild);
}