数据结构之树-二叉树(Java版本)(二)

2014-11-24 10:33:39 · 作者: · 浏览: 1
getLeftChild()); //访问左子树
preOrder(t.getRightChild()); //访问右子树
}
}

/**
* 对指定的二叉树执行中序遍历
* @param t 被遍历的二叉树根节点
*/
public static void inOrder(BinaryTreeNode t) {
if (t != null) {
inOrder(t.getLeftChild()); //访问二叉树的左子树
visit(t); //访问根
inOrder(t.getRightChild()); //访问二叉树的右子树
}
}

/**
* 对指定的二叉树执行后序遍历
* @param t 被遍历的二叉树的根节点
*/
public static void postOrder(BinaryTreeNode t) {
if (t != null) {
postOrder(t.getLeftChild()); //访问左子树
postOrder(t.getRightChild()); //访问右子树
visit(t); //访问根
}
}

/**
* 对指定的二叉树指定层序遍历
* 使用辅助队列
* @param t 被遍历的二叉树的根节点
*/
public static void levelOrder(BinaryTreeNode t) {
ArrayQueue q = new ArrayQueue(10);//辅助队列
while (t != null) {
visit(t);//访问根节点
if (t.getLeftChild() != null)
q.put(t.getLeftChild());//左孩子节点入列
if (t.getRightChild() != null)
q.put(t.getRightChild());//右孩子节点入列
t = (BinaryTreeNode) q.get();//取出下一个被访问的节点
}
}
}

[java]
/**
* 链接二叉树的实现
* @author Sking
*/
package 树.二叉树.链接二叉树;

import java.lang.reflect.*;

import 树.二叉树.*;
import 队列.ArrayQueue;

public class LinkedBinaryTree implements BinaryTree {
private BinaryTreeNode root;// 二叉树的根节点
static Method visit; // 访问节点的方法
static Object[] visitArgs = new Object[1]; // parameters of visit method
static int count; // counter
static Class< >[] paramType = { BinaryTreeNode.class };// 访问节点方法的参数类型
static Method theAdd1; // 实现计数器增加的方法
static Method theOutput; // 实现输出节点元素的方法
// method to initialize class data members
static {
try {

Class lbt = LinkedBinaryTree.class;
theAdd1 = lbt.getMethod("add1", paramType);
theOutput = lbt.getMethod("output", paramType);
} catch (Exception e) {
}
// exception not possible
}

// only default constructor available

// class methods
/** visit method that outputs element */
public static void output(BinaryTreeNode t) {
System.out.print(t.getElement() + " ");
}

/** visit method to count nodes */
public static void add1(BinaryTreeNode t) {
count++;
}

/**
* 判断二叉树是否为空
*/
public boolean isEmpty() {
return getRoot() == null;
}

public Object root() {
return (getRoot() == null) null : getRoot().getElement();
}

/**
* 返回根节点
*
* @return 二叉树的根节点
*/
public BinaryTreeNode getRoot() {
return root;
}

/**
* 设置二叉树的根节点
*
* @param root
* 设置后的根节点
*/
public void setRoot(BinaryTreeNode root) {
this.root = root;
}

/**
* set this to the tree with the given root and subtrees CAUTION: does not
* clone left and right
*/
public void makeTree(Object root, Object left, Object right) {
this.setRoot(new BinaryTreeNode(root, ((LinkedBinaryTree) left)
.getRoot(), ((LinkedBinaryTree) right).getRoot()));
}

/**
* remove the left subtree
*
* @throws IllegalArgumentException
* when tree is empty
* @return removed subtree
*/
public BinaryTree removeLeftSubtree()