美文网首页
二叉树的遍历

二叉树的遍历

作者: lintong | 来源:发表于2015-02-28 12:03 被阅读131次

二叉树深度遍历的代码

/* 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);
  }
}

相关文章

  • 二叉树 基础操作

    二叉树的使用 二叉树结构 先序创建二叉树 DFS 先序遍历二叉树 中序遍历二叉树 后序遍历二叉树 BFS 层次遍历...

  • 二叉树遍历

    二叉树 二叉树的存储结构 前序遍历 中序遍历 后序遍历 遍历代码 反转二叉树 深入学习二叉树 二叉树-你必须要懂!...

  • 二叉树操作

    树节点 逐行顺序解析二叉树 前序遍历二叉树 中序遍历二叉树 后序遍历二叉树 删除指定数值的节点 前序遍历顺序存储的...

  • 关于二叉树的算法题

    前序遍历中序遍历后序遍历判断是否是平衡二叉树判断是否是对称二叉树判断二叉树高度按照层遍历二叉树判断二叉树宽度

  • 二叉树三种遍历Swift代码实现

    二叉树的三种遍历 二叉树 前序遍历 中序遍历 后序遍历 另外 不得不说,得到二叉树的前序遍历和中序遍历的结果或者后...

  • 数据结构与算法之二叉树遍历(七)

    目录 前序遍历中序遍历后序遍历层序遍历遍历方式的选择条件根据遍历结果重构二叉树翻转二叉树计算二叉树的高度判断一棵树...

  • 二叉树的遍历

    二叉树的遍历 二叉树遍历 分为前序遍历、中序遍历和后序遍历。 前序遍历 (DLR) 先访问根节点,然后前序遍历左子...

  • 数据结构:树的实现和遍历(c++)

    (一)二叉树的遍历——递归实现 二叉树常见的遍历方式分为前序遍历、中序遍历和后序遍历。 1 前序遍历 前序遍历也叫...

  • 二叉树的蛇形层次遍历(LeetCode.103)

    题目 解析 首先参考二叉树的层次遍历层次遍历二叉树(LeetCode--102二叉树的层次遍历)[https://...

  • 算法精选题总结之二叉树类

    1.二叉树的中序遍历中序遍历的迭代方法中序遍历的递归方法2.二叉树前序遍历3.二叉树后续遍历4.二叉树的最近公共祖...

网友评论

      本文标题:二叉树的遍历

      本文链接:https://www.haomeiwen.com/subject/ggkpxttx.html