二叉树

来源:互联网 发布:淘宝卖家号出售 编辑:程序博客网 时间:2024/05/16 00:47

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 stubint[] 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); */}}



0 0
原创粉丝点击