作业帮 > 综合 > 作业

用非递归算法实现:统计二叉树中度为1的结点个数、度为2的结点个数和度为0的结点个数.

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/10/06 15:17:08
用非递归算法实现:统计二叉树中度为1的结点个数、度为2的结点个数和度为0的结点个数.
是非递归算法,数据结构的(C语言版)
调用时使用如下方式即可:
int result[3] = {0};
getNum(root, result);//其中root为根结点指针

typedef struct listnode{
TreeNode *root;
struct listnode * next;
}LISTNODE;

void getNum(TreeNode *root, int result[3])
{
LISTNODE * head, *rear *tmp;
head = NULL;
rear = NULL;
if (root != NULL)
{
rear = (LISTNODE *)malloc(sizeof(LISTNODE));
rear->root = root;
rear->next = NULL;
head = rear;
}

while(head != NULL)
{
int pos = 0;
if (head->root->left != NULL )
{
pos++;
rear->next = (LISTNODE *)malloc(sizeof(LISTNODE));
rear = rear->next;
rear->root = head->root->left;
rear->next = NULL;
}

if (head->root->right != NULL)
{
pos++;
rear->next = (LISTNODE *)malloc(sizeof(LISTNODE));
rear = rear->next;
rear->root = head->root->right;
rear->next = NULL;
}

result[pos]++;
tmp = head;
head = head->next;
free(tmp);
}
}