public class TreeNode<E> {
public E e;
public TreeNode<E> left;
public TreeNode<E> right;
public TreeNode(E e) {
this.e = e;
}
}
public class Main {
public static void main(String[] args) {
TreeNode<String> root = new TreeNode<>("A");
root.left = new TreeNode<>("B");
root.right = new TreeNode<>("E");
root.left.left = new TreeNode<>("C");
root.left.right = new TreeNode<>("D");
root.right.left = new TreeNode<>("F");
root.right.right = new TreeNode<>("G");
front(root);
System.out.println();
middle(root);
System.out.println();
rear(root);
}
// 部分子树也满足该规律
// 到达结点就输出,先左后右
// A B C D E F G
private static void front(TreeNode<String> root) {
if (root == null) return;
System.out.print(root.e + " ");
front(root.left);
front(root.right);
}
// 先输出左子树结点,再输出当前结点,最后右子树
// C B D A F E G
private static void middle(TreeNode<String> root) {
if (root == null) return;
middle(root.left);
System.out.print(root.e + " ");
middle(root.right);
}
// 先遍历左子树,再遍历右子树,最后输出结点本身
// C D B F G E A
private static void rear(TreeNode<String> root) {
if (root == null) return;
rear(root.left);
rear(root.right);
System.out.print(root.e + " ");
}
}
最简单二叉树模板(Java版)
最新推荐文章于 2022-10-23 21:07:09 发布