//定义二叉树节点
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//由链表创建树
TreeNode* createTree(int *list, int start)
{
if (list[start] == 0)
{
return NULL;
}
TreeNode* root = new TreeNode(list[start]);
int lnode = 2 * start + 1;
int rnode = 2 * start + 2;
if (lnode > sizeof(list) - 1) {
root->left = NULL;
}
else {
root->left = createTree(list, lnode);
}
if (rnode > sizeof(list) - 1) {
root->right = NULL;
}
else {
root->right = createTree(list, rnode);
}
return root;
}
void PreOrder(TreeNode * root) //先序遍历
{
if (root != NULL)
{
cout << root->val << " ";
PreOrder(root->left);
PreOrder(root->right);
}
}
void InOrder(TreeNode *root) //中序遍历
{
if (root != NULL)
{
InOrder(root->left);
cout << root->val << " ";
InOrder(root->right);
}
}
void PostOrder(TreeNode *root) //后序遍历
{
if (root != NULL)
{
PostOrder(root->left);
PostOrder(root->right);
cout << root->val << " ";
}
}
void LevelOrder(TreeNode *root) //层次遍历
{
int front, rear;
TreeNode *que[MaxSize];
front = rear = 0;
TreeNode *q;
if (root != 0)
{
rear = (rear + 1) % MaxSize;
que[rear] = root;
while (front != rear)
{
front = (front + 1) % MaxSize;
q = que[front];
cout << q->val << " ";
if (q->left != 0)
{
rear = (rear + 1) % MaxSize;
que[rear] = q->left;
}
if (q->right != 0)
{
rear = (rear + 1) % MaxSize;
que[rear] = q->right;
}
}
}
}