二叉树深度遍历的代码
/* Given a binary tree, print its nodes according to the
"bottom-up" postorder traversal. */
void printPostorder(struct node* node)
{
if (node == NULL)
return;
// first recur on left subtree
printPostorder(node->left);
// then recur on right subtree
printPostorder(node->right);
// now deal with the node
printf("%d ", node->data);
}
/* Given a binary tree, print its nodes in inorder*/
void printInorder(struct node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
printf("%d ", node->data);
/* now recur on right child */
printInorder(node->right);
}
/* Given a binary tree, print its nodes in inorder*/
void printPreorder(struct node* node)
{
if (node == NULL)
return;
/* first print data of node */
printf("%d ", node->data);
/* then recur on left sutree */
printPreorder(node->left);
/* now recur on right subtree */
printPreorder(node->right);
}
二叉树的遍历代码,遵循一个基本的代码框架。区别在于访问节点数据在什么时候。
二叉树的中序遍历可以对于排序二叉树的中序遍历可以获取升序序列。
对于二叉树的前序遍历可以复制一棵树。
二叉树的后序遍历可以删除一棵树。
二叉树宽度遍历
二叉树宽度遍历的代码
void printLevelOrder(struct node* root)
{
struct node **queue = createQueue(); //创建队列
struct node *temp_node = root;
while(temp_node)
{
printf("%d ", temp_node->data);
/*Enqueue left child */
if(temp_node->left)
enQueue(queue, temp_node->left);
/*Enqueue right child */
if(temp_node->right)
enQueue(queue, temp_node->right);
/*Dequeue node and make it temp_node*/
temp_node = deQueue(queue);
}
}