用非递归算法实现:统计二叉树中度为1的结点个数、度为2的结点个数和度为0的结点个数。
收起
知与谁同
2018-07-15 15:18:04
4334
0
1
条回答
写回答
取消
提交回答
-
调用时使用如下方式即可:
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);
}
}
2019-07-17 22:55:44