遍历二叉树的三种方法

先序遍历二叉树:

void PreOrder(BiTree root)   //root为指向二叉树(或某一子树)根结点的指针

{ if(root!=NULL)

  {

    Visit(root->data);    //访问根节点

    PreOrder(root->LChild);  //访问左子树

    PreOrder(root->RChild);  //访问右子树

  }

}

中序遍历二叉树:

void InOrder(BiTree root)   //root为指向二叉树(或某一子树)根结点的指针

{ if(root!=NULL)

  {

    InOrder(root->LChild);  //访问左子树

    Visit(root->data);    //访问根节点

    InOrder(root->RChild);  //访问右子树

  }

}

后序遍历二叉树:

void PostOrder(BiTree root)   //root为指向二叉树(或某一子树)根结点的指针

{ if(root!=NULL)

  {

    PostOrder(root->LChild);  //访问左子树

    PostOrder(root->RChild);  //访问右子树

    Visit(root->data);    //访问根节点

  }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
遍历二叉树方法三种:先序遍历、中序遍历和后序遍历。其中,先序遍历是指先遍历根节点,再遍历左子树和右子树;中序遍历是指先遍历左子树,再遍历根节点和右子树;后序遍历是指先遍历左子树和右子树,再遍历根节点。 线索二叉树是在二叉树的基础上,通过添加线索(即前驱和后继指针)来实现遍历的优化。线索二叉树遍历方法有两种:中序遍历和后序遍历。其中,中序遍历是指按照节点的中序遍历顺序遍历线索二叉树;后序遍历是指按照节点的后序遍历顺序遍历线索二叉树。 举例说明: ```java //先序遍历二叉树 public void preOrder(TreeNode root) { if (root != null) { System.out.print(root.val + " "); preOrder(root.left); preOrder(root.right); } } //中序遍历二叉树 public void inOrder(TreeNode root) { if (root != null) { inOrder(root.left); System.out.print(root.val + " "); inOrder(root.right); } } //后序遍历二叉树 public void postOrder(TreeNode root) { if (root != null) { postOrder(root.left); postOrder(root.right); System.out.print(root.val + " "); } } //中序遍历线索二叉树 public void inOrderThreaded(TreeNode root) { TreeNode cur = root; while (cur != null) { while (cur.left != null && !cur.left.isThreaded) { cur = cur.left; } System.out.print(cur.val + " "); if (cur.right != null && cur.isThreaded) { cur = cur.right; } else { cur = cur.right; while (cur != null && !cur.isThreaded) { cur = cur.left; } } } } //后序遍历线索二叉树 public void postOrderThreaded(TreeNode root) { TreeNode cur = root; while (cur != null) { while (cur.left != null && !cur.left.isThreaded) { cur = cur.left; } while (cur.right != null && cur.isThreaded) { System.out.print(cur.val + " "); cur = cur.right; } System.out.print(cur.val + " "); cur = cur.right; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值