树(二)二叉树递归和非递归遍历

本文介绍了二叉树的递归和非递归遍历方法,包括前序、中序和后序遍历。在非递归遍历中,利用栈来模拟递归过程,重点阐述了前序、中序和后序遍历的步骤,特别是中序和后序遍历的节点访问和入栈顺序。此外,还探讨了深度优先搜索(DFS)和层次遍历(BFS)的概念。
摘要由CSDN通过智能技术生成

1、递归遍历

// 先序遍历(递归实现)-------------------------------------------------------------
 	  /*
	  1. Visit the node.
	  1. Call itself to traverse the node’s left subtree.
      3. Call itself to traverse the node’s right subtree.
	  4. base case: there is no node
	  */
   private void preOrder(Node localRoot){
      if(localRoot != null)
         {
         visit(localRoot);       // System.out.print(localRoot.iData + " ");
         preOrder(localRoot.leftChild);
         preOrder(localRoot.rightChild);
         }
      }
// 中序遍历(递归实现)-------------------------------------------------------------
   private void inOrder(Node localRoot){
      if(localRoot != null)
         {
         inOrder(localRoot.leftChild);
         visit(localRoot);       //System.out.print(localRoot.iData + " ");
         inOrder(localRoot.rightChild);
         }
      }
// 后序遍历(递归实现)-------------------------------------------------------------
   private void postOrder(Node localRoot){
      if(localRoot != null)
         {
         postOrder(localRoot.leftChild);
         postOrder(localRoot.rightChild);
         visit(localRoot);       //System.out.print(localRoot.iData + " ");
         }
      }
// -------------------------------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值