关于树的大部分知识点我们都讲过了,那么如果我给你树的节点,你可以算出叶子节点个数吗?
下面我们总结下一些计算规则:
1.父子计算规则:
parent=(child-1)/2;
leftchild=parent*2+1,rightchild=parent*2+2;
2.若规定根节点的层数为1,则一棵非空二叉树的第i层上最多有2^(i-1)个节点
3.深度为h的二叉树的最大结点数是2^h-1;
4. 对任何一棵二叉树, 如果度为0其叶结点个数为N0?, 度为2的分支结点个数为N2 ,则有
// 层序遍历定义(一:一起遍历)
void LevelOrder(TreeNode* root)
{
Queue s1;
QueueInit(&s1);
//判断是否为空,不空的话,先压进一个
if(root)
QueuePush(&s1, root);
while (!QueueEmpty(&s1))
{
TreeNode* cur = QueueFront(&s1);
QueuePop(&s1);
printf("%d ", cur->date);
//压入它的左右孩子
if(root->left)
QueuePush(&s1, root->left);
if (root->right)
QueuePush(&s1, root->right);
}
printf("\n");
}
//动态开辟空间定义
TreeNode* BuyTreeNode(int x)
{
//开辟树的空间
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
assert(node);
node->date = x;
node->left = NULL;
node->right = NULL;
return node;
}
//建立二叉树定义
TreeNode* CreateTree()
{
//开辟树并且对每个进行赋值
TreeNode* node1 = BuyTreeNode(1);
TreeNode* node2 = BuyTreeNode(2);
TreeNode* node3 = BuyTreeNode(3);
TreeNode* node4 = BuyTreeNode(4);
TreeNode* node5 = BuyTreeNode(5);
TreeNode* node6 = BuyTreeNode(6);
//确定指向
node1->left = node2;
node1->right = node4;
node2->left = node3;
node4->left = node5;
node4->right = node6;
return node1;
}
int main()
{
TreeNode* root = CreateTree();
LevelOrder(root);
BinaryTreeDestory1(root);
root = NULL;
return 0;
}
结果:
// 层序遍历定义(二:逐层遍历)
void LevelOrder2(TreeNode* root)
{
Queue s1;
QueueInit(&s1);
int size = 1;
//判断是否为空,不空的话,先压进一个
if (root != NULL)
QueuePush(&s1, root);
while (!QueueEmpty(&s1))
{
while (size>0)
{
TreeNode* cur = QueueFront(&s1);
QueuePop(&s1);
printf("%d ", cur->date);
//压入它的左右孩子
if (cur->left)
QueuePush(&s1, cur->left);
if (cur->right)
QueuePush(&s1, cur->right);
size--;
}
printf("\n");
size = QueueSize(&s1);
}
printf("\n");
}
结果:(还是上面的树)
//判断二叉树是否是完全二叉树
bool BinaryTreeComplete(TreeNode* root)
{
Queue s1;
QueueInit(&s1);
//判断是否为空,不空的话,先压进一个
if (root != NULL)
QueuePush(&s1, root);
//找到第一个空
while (!QueueEmpty(&s1))
{
TreeNode* cur = QueueFront(&s1);
QueuePop(&s1);
if (cur == NULL)
break;
//压入它的左右孩子,注意:不用判断了
QueuePush(&s1, cur->left);
QueuePush(&s1, cur->right);
}
//第二步:如果在栈中还有非空,就说明不是完全二叉树
//定理:如果不是完全二叉树,那么栈里面此时一定有数据了
while (!QueueEmpty(&s1))
{
TreeNode* cur2 = QueueFront(&s1);
QueuePop(&s1);
if (cur2 != NULL)
return false;
}
return true;
}
检查:
//建立二叉树定义
TreeNode* CreateTree()
{
//开辟树并且对每个进行赋值
TreeNode* node1 = BuyTreeNode(1);
TreeNode* node2 = BuyTreeNode(2);
TreeNode* node3 = BuyTreeNode(3);
TreeNode* node4 = BuyTreeNode(4);
TreeNode* node5 = BuyTreeNode(5);
TreeNode* node6 = BuyTreeNode(6);
TreeNode* node7 = BuyTreeNode(7);
//确定指向
node1->left = node2;
node1->right = node4;
node2->left = node3;
node2->right = node7;
node4->left = node5;
//node3->left = node5;
node4->right = node6;
return node1;
}