1:二叉树的建立
package 二叉树;
public class BinaryTree {
int data;// 根节点数据
public BinaryTree left;
public BinaryTree right;
public BinaryTree(int data) { // 实例化二叉树类
this.data = data;
left = null;
right = null;
}
public void insert(BinaryTree root, int data)// 向二叉树中插入子节点
{
if (data > root.data) { // 二叉树的左节点都比根节点小
if (root.right == null) {
root.right = new BinaryTree(data);
} else {
this.insert(root.right, data);
}
} else {
if (root.left == null) {
root.left = new BinaryTree(data);
} else {
this.insert(root.left, data);
}
}
}
}
二: 二叉树的(前向遍历、中序遍历、后序遍历),二叉树的深度和宽度
package 二叉树;
import java.nio.channels.ShutdownChannelGroupException;
import java.util.ArrayDeque;
import java.util.Queue;
public class BinaryTreePreorder {
public static void preOrder(BinaryTree root) {// 前向遍历
if (root != null) {
System.out.print(root.data + "-");
preOrder(root.left);
preOrder(root.right);
}
}
public static void middleOrder(BinaryTree root) // 中序遍历
{
if (root != null) {
middleOrder(root.left);
System.out.print(root.data + "-");
middleOrder(root.right);
}
}
public static void afterOrder(BinaryTree root) {// 后续遍历
if (root != null) {
afterOrder(root.left);
afterOrder(root.right);
System.out.print(root.data);
}
}
/* 树的高度 */
public static int getMaxPath(BinaryTree root) {
if (root == null) {
return 0;
} else {
int left = getMaxPath(root.left);
int right = getMaxPath(root.right);
return 1 + Math.max(left, right);
}
}
/* 树的宽度 */
public static int getMaxWidth(BinaryTree root) {
if (root == null) {
return 0;
}
Queue<BinaryTree> queue = new ArrayDeque<BinaryTree>(); // java的队列
int maxWidth = 1;
queue.add(root); // 入队
while (true) {
int len = queue.size();
if (len == 0) {
break;
}
while (len > 0) {
BinaryTree b = queue.poll();// 出队
len--;
if (b.left != null) {
queue.add(b.left);
}
if (b.right != null) {
queue.add(b.right);
}
maxWidth = Math.max(maxWidth, queue.size());
}
}
return maxWidth;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = { 12, 76, 35, 22, 16, 48, 90, 46, 9, 40 };
BinaryTree root = new BinaryTree(array[0]);// 创建二叉树
for (int i = 1; i < array.length; i++) {
root.insert(root, array[i]);
}
System.out.println("前向遍历");
preOrder(root);
System.out.println();
System.out.println("中序遍历");
middleOrder(root);
System.out.println();
System.out.println("后续遍历");
afterOrder(root);
System.out.println();
System.out.println("树的宽度");
System.out.println(getMaxWidth(root));
System.out.println("树的高度");
System.out.println(getMaxPath(root));
/* int b=getMaxDepth(root); */
}
}