二叉树的java实现与几种遍历
来源:互联网 发布:全球网络连接七彩图 编辑:程序博客网 时间:2024/05/17 02:38
package com.tree;public class BinaryTree {private int data;//数据节点private BinaryTree left;private BinaryTree right;public BinaryTree(int data){this.data = data;this.left = null;this.right = null;}/* * 创建二叉树,返回根节点 * @param input * @return */public static BinaryTree createTree(int[] input){BinaryTree root = null;BinaryTree temp = null;for(int i = 0; i < input.length;i++){//创建根节点if(root == null){root = temp = new BinaryTree(input[i]);}else{temp = root;//添加节点while(temp.data != input[i]){if(input[i] <= temp.data){if(temp.left != null){temp = temp.left;}else{temp.left = new BinaryTree(input[i]);}}else{if(temp.right != null){temp = temp.right;}else{temp.right = new BinaryTree(input[i]);}}}}}return root;}/* * 前序遍历 * @param tree */public static void preOrder(BinaryTree tree){if(tree != null){System.out.println(tree.data);preOrder(tree.left);preOrder(tree.right);}}/* * 中序遍历 * @param tree */public static void midOrder(BinaryTree tree){if(tree != null){midOrder(tree.left);System.out.println(tree.data);midOrder(tree.right);}}/* * 后序遍历 * @param tree */public static void posOrder(BinaryTree tree){if(tree != null){posOrder(tree.left);posOrder(tree.right);System.out.println(tree.data);}}/* * 求二叉树的深度 * * @param tree */public static int length(BinaryTree tree){int leftLen;int rightLen;if(tree == null){return 0;}else{leftLen = length(tree.left);rightLen = length(tree.right);if(leftLen > rightLen){return leftLen+1;}else{return rightLen+1;}}}/* * 测试main函数 * * @param args */public static void main(String[] args){int[] input = {4,2,6,1,3,5,7,8,10};BinaryTree btree = createTree(input);System.out.println("前序遍历:");preOrder(btree);System.out.println("中序遍历:");midOrder(btree);System.out.println("后序遍历:");posOrder(btree);System.out.println("树的深度:"+length(btree));}}
0 0
- 二叉树的java实现与几种遍历
- 二叉树的几种遍历递归与非递归java实现
- 二叉树的几种遍历(递归,非递归)JAVA实现
- 二叉树的几种遍历(C实现)
- 二叉查找树的构造与遍历[Java实现]
- 二叉查找树的构造与遍历[Java实现]
- Java实现二叉树的递归与非递归遍历
- 二叉树的几种遍历方式
- 二叉树的几种遍历
- 二叉树的几种遍历方法
- 二叉树的几种遍历方法
- 二叉树的几种遍历方式
- 二叉树的实现与遍历
- 二叉树与遍历的Python实现
- 二叉树的遍历(Java实现)
- Java实现二叉树的多种遍历
- 二叉树的遍历Java实现_world
- Java实现二叉树的遍历
- bash:crontab:command not found
- Oracle 11g服务详细介绍及哪些服务是必须开启的?
- Android的fill_parent和wrap_content的区别
- 负载均衡
- 记调试MKL MATLAB接口
- 二叉树的java实现与几种遍历
- comparator接口与Comparable接口的区别
- 第11周程序1
- loadFileSystems error & ExceptionUtils错误原因分析
- 高精度之大数乘大数
- Pig源码分析: 简析执行计划的生成
- libjpeg与turbo libjpeg的使用
- android打开文件的工具
- 两个相等的值 经过if 判断后不等于了