实现二叉排序树, 并分别用先序、中序、后序输出
来源:互联网 发布:excel数据统计怎么做 编辑:程序博客网 时间:2024/04/28 20:48
public class TreeTest {class TreeNode {int val;TreeNode leftNode;TreeNode rightNode;public TreeNode(int val) {this.val = val;leftNode = null;rightNode = null;} }private TreeNode root = null;/*构建一棵二叉排序树*/public void buildTree(int[] array) {for(int i=0; i<array.length; i++) {insertNode(array[i]);}}public void insertNode(int data) {TreeNode newNode = new TreeNode(data);if(root == null) {root = newNode;} else {TreeNode current = root;TreeNode parent;while(true) {parent = current;if(data < current.val) {current = current.leftNode;if(current == null) {parent.leftNode = newNode;return;}} else {current = current.rightNode;if(current == null) {parent.rightNode = newNode;return;}}}}}/** * 先序遍历 * */public void firstTrace(TreeNode root) {if(root != null) {System.out.print(root.val+" ");firstTrace(root.leftNode);firstTrace(root.rightNode);}}public void firstTrace() {this.firstTrace(this.root);}/** * 中序遍历 * */public void midTrace(TreeNode root) {if(root != null) {midTrace(root.leftNode);System.out.print(root.val+" ");midTrace(root.rightNode);} }public void midTrace() {this.midTrace(root);}/** * 后序遍历 * */public void postTrace(TreeNode root) {if(root != null) {postTrace(root.leftNode);postTrace(root.rightNode);System.out.print(root.val+" ");}}public void postTrace() {this.postTrace(root);}/** * 测试 * */public static void main(String[] args) {TreeTest tt = new TreeTest();int[] array = {2, 8, 7, 4, 9, 3, 1, 6, 7, 5};tt.buildTree(array);tt.firstTrace();System.out.println();tt.midTrace();System.out.println();tt.postTrace();}}
0 0
- 实现二叉排序树, 并分别用先序、中序、后序输出
- 建立二叉排序树,并前后序输出
- 生成二叉排序树并先序遍历、中序遍历、后序遍历
- 根据输入的数据,建立二叉排序树,并求先、中、后序遍历
- JAVA创建二叉树将数组中的数依次存入二叉树,并分别用先序,后序,中序遍历;
- 二叉排序树后序判断
- 二叉排序树的创建,以及前序、中序、后序遍历的递归实现
- 用java构建二叉排序树,实现先序,中序和后序遍历
- 05年华中科大机试第三题(输入一个字符串,建立一个二叉排序树,并中序遍历输出)
- Java实现由前序序列和中序序列重建二叉树,并后序输出。
- 二叉搜素树 二叉排序树 插入 删除 中序输出
- 数据结构:树的遍历!按先序遍历创建一棵树,分别以先序、中序、后序遍历输出
- 数据结构 分别用递归和非递归方法实现二叉树先序,中序,后序遍历
- 二叉排序树的建立 前序 中序 后序 遍历
- 二叉排序树(插入操作与前、中、后序遍历)
- 二叉排序树(C与Python分别实现)
- 分别用递归和非递归方式实现二叉树先序、中序和后序遍历(java实现)
- 由先序和中序构造二叉树并后序输出
- 【iOS】AFNetworking断点下载
- 从 this 指针获得一个shared_ptr: enable_shared_from_this
- 在ScrollView中使用GridView和ListView
- 学习windows驱动(设备对象设备栈)
- ehcache memcache redis 三大缓存男高音
- 实现二叉排序树, 并分别用先序、中序、后序输出
- 硬件加速器
- 通知
- Android Activity 、 Window 、 View之间的关系
- 异常处理
- Unity3d 用TextAsset打包加密
- 如何避免FragmentTabHost切换Fragment时重复加载UI
- *LeetCode-Walls and Gates
- 21 Amicable numbers - Project Euler