下面代码包含了二叉树的建立过程,以及三种遍历方法了递归实现,代码中还利用队列实现了层次遍历。
import java.util.LinkedList; import java.util.Queue; class TreeNode<K> { TreeNode<K> left, right; K key; public TreeNode(K k) { left = null; right = null; key = k; } } class BinaryTree<K extends Comparable<K> > { //添加 extends Comparable<K>后,K对象可以进行比较。 TreeNode<K> root; public BinaryTree() { root = null; } public void createTree(TreeNode<K> node, K data) { //建立二叉树 if(root == null) { root = new TreeNode<K>(data); } else { if(data.compareTo(node.key) < 0) { if(node.left == null) node.left = new TreeNode<K>(data); else createTree(node.left, data); } else { if(node.right == null) node.right = new TreeNode<K>(data); else createTree(node.right, data); } } } public void preOrder(TreeNode<K> root) { //前序遍历 if(root != null) { System.out.println(root.key); preOrder(root.left); preOrder(root.right); } } public void inOrder(TreeNode<K> root) { //中序遍历 if(root != null) { inOrder(root.left); System.out.println(root.key); inOrder(root.right); } } public void postOrder(TreeNode<K> root) { //后序遍历 if(root != null) { postOrder(root.left); postOrder(root.right); System.out.println(root.key); } } public void levelOrder(TreeNode<K> root) { //层次遍历 if(root != null) { Queue<TreeNode<K>> queue = new LinkedList<TreeNode<K>>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode<K> node = queue.poll(); System.out.println(node.key); if(node.left != null) queue.offer(node.left); if(node.right != null) queue.offer(node.right); } } } } public class TestClass { public static void main(String[] args) { int[] array = {6, 8, 7, 5, 2, 5}; BinaryTree<Integer> bt = new BinaryTree<Integer>(); for (int i = 0; i < array.length; i++) { bt.createTree(bt.root, array[i]); } // bt.preOrder(bt.root); // bt.inOrder(bt.root); // bt.postOrder(bt.root); bt.levelOrder(bt.root); } }