二叉树java实现
/** * 链表实现二叉树 * -创建二叉树 * -前序、中序、后序、层次遍历二叉树 * -判断值是否存在 * -二叉树高度 */ public class BinaryTree { // 链表节点 public static class Node { public String val; public Node left; public Node right; public Node() { } public Node(String val) { this.val = val; } } /** * 创建二叉树(需要辅助变量 i) * 通过前序字符串 String[] {"A", "B","#", "#", "C", "#", "#"} 来创建 * 注意:必须是前序字符串 * #表示空节点 */ private static int i = 0; // 利用前序字符串数组自动创建 public static Node createBTree(String[] arr) { if ("#".equals(arr[i])) { i++; return null; } Node root = new Node(arr[i++]); root.left = createBTree(arr); root.right = createBTree(arr); return root; } // 手动创建(输入顺序必须是前序序列) public static Node handCreate() { Scanner scanner = new Scanner(System.in); System.out.println("请输入节点元素:"); String next = scanner.next(); Node root = new Node(next); if ("#".equals(next)) return null; root.left = handCreate(); root.right = handCreate(); return root; } // 前序遍历 public static void preOrder(Node root) { if (root == null) return; System.out.print(root.val + "\t"); preOrder(root.left); preOrder(root.right); } // 中序遍历 public static void inOrder(Node root) { if (root == null) return; inOrder(root.left); System.out.print(root.val + "\t"); inOrder(root.right); } // 后序遍历 public static void afterOrder(Node root) { if (root == null) return; afterOrder(root.left); afterOrder(root.right); System.out.print(root.val + "\t"); } // 层次遍历 public static void levelOrder(Node root) { Queue<Node> queue = new LinkedList<>(); // 先将根节点入队 queue.add(root); // 遍历,直到队列为空 while (!queue.isEmpty()) { // 出队输出 Node pollNode = queue.poll(); System.out.print(pollNode.val + "\t"); // 如果左子树不为空,入队 if (pollNode.left != null) { queue.add(pollNode.left); } // 如果右子树不为空,入队 if (pollNode.right != null) { queue.add(pollNode.right); } } } // 二叉树中是否存在指定值 public static boolean isExist(Node root, String val) { if (root == null) return false; if (val.equals(root.val)) return true; boolean l = isExist(root.left, val); boolean r = isExist(root.right, val); return l || r; } // 二叉树高度 public static int getHeight(Node root) { if (root == null) return 0; int lHeight = getHeight(root.left); int rHeight = getHeight(root.right); return Math.max(lHeight, rHeight) + 1; } // main public static void main(String[] args) { // 前序字符串数组 String[] arr1 = {"A", "B", "D", "#", "#", "E", "#", "#", "C", "#", "#"}; String[] arr2 = {"A", "B", "#", "#", "C", "#", "#"}; Node root = BinaryTree.createBTree(arr2); System.out.println("前序遍历:"); BinaryTree.preOrder(root); System.out.println(); System.out.println("中序遍历:"); BinaryTree.inOrder(root); System.out.println(); System.out.println("后序遍历:"); BinaryTree.afterOrder(root); System.out.println(); System.out.println("层次遍历:"); BinaryTree.levelOrder(root); System.out.println(); System.out.println("二叉树高度:" + BinaryTree.getHeight(root)); System.out.println("是否存在:" + BinaryTree.isExist(root, "C")); } }