定义简单的树 package tree; /** */ /** * 二叉树的定义类 * @author root * */ public class BinarySearchTree ... { /** *//** * 存储的值 */ protected int key; /** *//** * 左节点 */ protected BinarySearchTree left; /** *//** * 右节点 */ protected BinarySearchTree right; public BinarySearchTree()...{ this.left = this.right = null; } public BinarySearchTree(int key)...{ this(key,null,null); } public BinarySearchTree(int key,BinarySearchTree left,BinarySearchTree right)...{ this.key = key; this.left = left; this.right = right; }} 遍历树,广度优先遍历 /** */ /** * 广度优先遍历二叉树 * * @author root * */ public class BreadthFirstTraversal ... { /** *//** * 广度优先遍历:(此方法的为由上到下,由左到右遍历) 张磊 2007-6-7 * * @param bin */ public List<Integer> traversal(BinarySearchTree bin) ...{ // java.util.concurrent允许多线程修改 ArrayBlockingQueue<BinarySearchTree> au = new ArrayBlockingQueue<BinarySearchTree>( 1024, true); if (bin != null) au.offer(bin); List<Integer> list = new ArrayList<Integer>(); BinarySearchTree bina = null; while (!au.isEmpty()) ...{ bina = (BinarySearchTree) au.poll(); list.add(bina.key); if (bina.left != null) ...{ au.offer(bina.left); } if (bina.right != null) ...{ au.offer(bina.right); } } return list; } public static void main(String[] args) ...{ /**//* * 验证广度优先遍历 * 13 * / * 10 25 * / / * 2 12 20 31 * / * 29 */ BinarySearchTree tree = new BinarySearchTree(13, new BinarySearchTree( 10, new BinarySearchTree(2, null, null), new BinarySearchTree( 12, null, null)), new BinarySearchTree(25, new BinarySearchTree(20, null, null), new BinarySearchTree(31, new BinarySearchTree(29, null, null), null))); BreadthFirstTraversal b = new BreadthFirstTraversal(); List<Integer> list = b.traversal(tree); Iterator it = list.iterator(); while(it.hasNext())...{ System.out.println(it.next()); } } 归并法删除节点 package tree; /** */ /** * 归并删除节点的类 * @author root * */ public class DeleteByMerging ... { /** *//** * 归并删除节点的方法 * 张磊 *2007-6-11 *@param key *@param tree *@return */ public BinarySearchTree deleteByMerging(int key,BinarySearchTree tree)...{ //先找到key对应的节点 BinarySearchTree p = tree; while(p != null && p.key != key)...{ if(key > p.key) p = p.right; else p = p.left; } //寻找此节点的左子树的最右节点 return tree; }} 插入新节点 package tree; /** */ /** * 向二叉树插入新节点 * @author root * */ public class InsertNewNode ... { /** *//** * 向二叉树插入新节点 * 张磊 *2007-6-11 *@param key *@param tree *@return */ public BinarySearchTree insertNode(int key,BinarySearchTree tree)...{ //找到适合它的空节点 while(tree != null)...{ if(key > tree.key) tree = tree.right; else tree = tree.left; } //判断在这个空节点上新节点插入到左右哪个分支 BinarySearchTree p = new BinarySearchTree(key); if(key>tree.key) tree.left = p; else tree.right = p; return tree; }} 简单的二叉树搜索 package tree; /** */ /** * 二叉查找树的简单搜索算法--简单的思路 * @author root * */ public class SearchTree ... { public BinarySearchTree search(BinarySearchTree node,int key)...{ while(node != null)...{ if(key == node.key)...{ return node; }else if(key<node.key)...{ node = node.left; }else...{ node = node.right; } } return null; }}