二叉树是一种常见的数据结构,它是由节点和连接节点的边组成的。每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树算法包括遍历、查找、插入、删除等操作。
class Node {int data;Node left, right;public Node(int item) {data = item;left = right = null;}
}class BinaryTree {Node root;void printPostorder(Node node) {if (node == null)return;printPostorder(node.left);printPostorder(node.right);System.out.print(node.data + " ");}void printInorder(Node node) {if (node == null)return;printInorder(node.left);System.out.print(node.data + " ");printInorder(node.right);}void printPreorder(Node node) {if (node == null)return;System.out.print(node.data + " ");printPreorder(node.left);printPreorder(node.right);}void printPostorder() {printPostorder(root);}void printInorder() {printInorder(root);}void printPreorder() {printPreorder(root);}public static void main(String[] args) {BinaryTree tree = new BinaryTree();tree.root = new Node(1);tree.root.left = new Node(2);tree.root.right = new Node(3);tree.root.left.left = new Node(4);tree.root.left.right = new Node(5);System.out.println("Preorder traversal of binary tree is:");tree.printPreorder();System.out.println("\nInorder traversal of binary tree is:");tree.printInorder();System.out.println("\nPostorder traversal of binary tree is:");tree.printPostorder();}
}
这个案例中,我们定义了一个Node类表示二叉树的节点,包含一个整型数据和左右子节点。BinaryTree类包含了打印前序遍历、中序遍历和后序遍历的方法。在main方法中,我们创建了一个二叉树实例,并调用相应的方法进行遍历。