面试过程遇到关于二叉树的问题

用java语言遍历二叉树,这是个程序设计题;按要求我的解答是这样的:

先写一个接口Visit

  1. package datastructure.tree;  
  2. /** 
  3.  * 对结点进行操作的接口 
  4.  * @author Administrator 
  5.  * 
  6.  */  
  7. public interface Visit {  
  8.     /** 
  9.      * 对结点进行某种操作 
  10.      * @param btree 树的结点 
  11.      */  
  12.     public void visit(BTree btree);  
  13. }
对二叉树进行遍历

  1. package datastructure.tree;  
  2. /** 
  3.  * 遍历二叉树 
  4.  * @author Administrator 
  5.  * 
  6.  */  
  7. public class OrderBTree implements Visit{  
  8.     /** 
  9.      * 前序遍历 
  10.      * @param root 根结点 
  11.      */  
  12.     public void preOrder(BTree root) {  
  13.         visit(root);  
  14.         if(root.getLeftChild() != null) {  
  15.             preOrder(root.getLeftChild());  
  16.         }  
  17.         if(root.getRightChild() != null) {  
  18.             preOrder(root.getRightChild());  
  19.         }  
  20.     }  
  21.     /** 
  22.      * 中序遍历 
  23.      * @param root 根结点 
  24.      */  
  25.     public void inOrder(BTree root) {  
  26.         if(root.getLeftChild() != null)  
  27.             inOrder(root.getLeftChild());  
  28.         visit(root);  
  29.         if(root.getRightChild() != null) {  
  30.             //System.out.println("true");  
  31.             inOrder(root.getRightChild());  
  32.         }  
  33.     }  
  34.     /** 
  35.      * 后序遍历 
  36.      * @param root 根结点 
  37.      */  
  38.     public void postOrder(BTree root) {  
  39.         if(root.getLeftChild() != null)  
  40.             postOrder(root.getLeftChild());  
  41.         if(root.getRightChild() != null)  
  42.             postOrder(root.getRightChild());  
  43.         visit(root);  
  44.     }  
  45.   
  46.     @Override  
  47.     public void visit(BTree btree) {  
  48.         System.out.print(btree.getRootData() + "\t");  
  49.     }  
  50.   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值