提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
访问方向图示:(后续解题思路)
ps:以中序遍历为例
//Preorder,Inorder,postorder,代码区别在于打印位置
void Order(BTNode* root) {
if (root == NULL) {
printf("NULL ");
return;
}
printf("%d ", root->data);//Preorder前序
Order(root->left);
printf("%d ", root->data);//Inorder中序
Order(root->right);
printf("%d ", root->data);//postorder后序
}
节点
typedef int BTDataType;
typedef struct BinaryTreeNode
{
BTDataType data;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
void LevelOrder(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root)
QueuePush(&q, root);//入队列
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);//保存队列头指针
QueuePop(&q);//出队列
printf("%d ", front->data);
if(front->left)
QueuePush(&q, front->left);
if (front->right)
QueuePush(&q, front->right);
}
QueueDestroy(&q);
}
原理解析:利用层序遍历,将二叉树遍历完。此时栈中只剩下NULL。只要清空栈的过程中发现非空元素则能够判断其不是完全二叉树,反之成立。
代码实现:
int TreeSize(BTNode* root)
{
return root == NULL ? 0 :
TreeSize(root->left)
+ TreeSize(root->right)
+ 1;
}
int TreeHeight(BTNode* root)
{
if (root == NULL)
return 0;
int leftHeight = TreeHeight(root->left);//保存递归的值
int rightHeight = TreeHeight(root->right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
int TreeKLevel(BTNode* root, int k)
{
assert(k > 0);
if (root == NULL)
return 0;
if (k == 1)
return 1;
return TreeKLevel(root->left, k - 1)
+ TreeKLevel(root->right, k - 1);
}
void TreeDestory()
{
if(root==NULL)
{
return;
}
TreeDestory(root->left);
TreeDestory(root->right);
free(root);
}