用java语言遍历二叉树,这是个程序设计题;按要求我的解答是这样的:
先写一个接口Visit
- package datastructure.tree;
- /**
- * 对结点进行操作的接口
- * @author Administrator
- *
- */
- public interface Visit {
- /**
- * 对结点进行某种操作
- * @param btree 树的结点
- */
- public void visit(BTree btree);
- }
- package datastructure.tree;
- /**
- * 遍历二叉树
- * @author Administrator
- *
- */
- public class OrderBTree implements Visit{
- /**
- * 前序遍历
- * @param root 根结点
- */
- public void preOrder(BTree root) {
- visit(root);
- if(root.getLeftChild() != null) {
- preOrder(root.getLeftChild());
- }
- if(root.getRightChild() != null) {
- preOrder(root.getRightChild());
- }
- }
- /**
- * 中序遍历
- * @param root 根结点
- */
- public void inOrder(BTree root) {
- if(root.getLeftChild() != null)
- inOrder(root.getLeftChild());
- visit(root);
- if(root.getRightChild() != null) {
- //System.out.println("true");
- inOrder(root.getRightChild());
- }
- }
- /**
- * 后序遍历
- * @param root 根结点
- */
- public void postOrder(BTree root) {
- if(root.getLeftChild() != null)
- postOrder(root.getLeftChild());
- if(root.getRightChild() != null)
- postOrder(root.getRightChild());
- visit(root);
- }
- @Override
- public void visit(BTree btree) {
- System.out.print(btree.getRootData() + "\t");
- }
- }