节点Node:
package TreeExercise;
public class TreeNode<T> {
public T data;
public TreeNode<T> left;
public TreeNode<T> right;
public TreeNode(T t) {
data = t;
left = null;
right = null;
}
}
树的基本方法:
package TreeExercise;
import java.util.Scanner;
public class MyTree<T extends Comparable> {
//根节点
public TreeNode<T> root;
public MyTree() {
root = new TreeNode<T>(null);
}
//创建查找二叉树
public void buildTree(TreeNode<T> node, T data) {
if (root == null) {
root = new TreeNode<T>(data);
} else {
if (data.compareTo(node.data) < 0) {
if (node.left == null) {
node.left = new TreeNode<T>(data);
} else {
buildTree(node, data);
}
} else {
if (node.right == null) {
node.right = new TreeNode<T>(data);
} else {
buildTree(node, data);
}
}
}
}
public void createTree() {
Scanner sanner = new Scanner(System.in);
root = createTreeNode(root, sanner);
}
//前序遍历生成二叉树
private TreeNode<T> createTreeNode(TreeNode<T> node, Scanner scanner) {
T data = (T) scanner.nextLine();
if ("/".equals(data)) {
return null;
} else {
node = new TreeNode<T>(data);
node.left = createTreeNode(node.left, scanner);
node.right = createTreeNode(node.right, scanner);
}
return node;
}
//region 递归遍历二叉树
//中序遍历
public void orderTraverse() {
// System.out.println("中序遍历");
System.out.println("orderTraverse");
orderTraverse(root);
System.out.println();
}
private void orderTraverse(TreeNode<T> node) {
if (node == null) return;
orderTraverse(node.left);
System.out.println((T) node.data);
orderTraverse(node.right);
}
//前序遍历
public void preOrderTraverse() {
// System.out.println("前序遍历");
System.out.println("orderTraverse");
preOrderTraverse(root);
System.out.println();
}
private void preOrderTraverse(TreeNode<T> node) {
if (node == null) return;
System.out.println(node.data);
orderTraverse(node.left);
orderTraverse(node.right);
}
//后序遍历
public void postOrderTraverse() {
// System.out.println("后序遍历");
System.out.println("postOrderTraverse");
postOrderTraverse(root);
System.out.println();
}
private void postOrderTraverse(TreeNode<T> node) {
if (node == null) return;
orderTraverse(node.left);
orderTraverse(node.right);
System.out.println(node.data);
}
//endregion
}
网友评论