二叉树之实现排序二叉树
2015-10-22 08:51
204 查看
package me.wcy.j2se.datastructure; /** * 排序二叉树 * * @author chenyan.wang * */ public class BinaryTree { public static void main(String[] args) { BinaryTree biTree = new BinaryTree(); int[] data = { 2, 8, 7, 4, 9, 3, 1, 6, 7, 5 }; biTree.buildTree(data); System.out.print("中序遍历:"); biTree.inOrder(); System.out.println(); System.out.print("先序遍历:"); biTree.preOrder(); System.out.println(); System.out.print("后序遍历:"); biTree.postOrder(); System.out.println(); } private TreeNode root; public BinaryTree() { } /** * 将data插入到排序二叉树中 * * @param data */ public void insert(int data) { TreeNode node = new TreeNode(data); if (root == null) { root = node; } else { TreeNode current = root; TreeNode parent; while (true) {// 寻找插入位置 parent = current; if (data < parent.data) { current = parent.left; if (current == null) { parent.left = node; return; } } else { current = parent.right; if (current == null) { parent.right = node; return; } } } } } /** * 将数值输入构建二叉树 * * @param data */ public void buildTree(int[] data) { for (int n : data) { insert(n); } } /** * 中序遍历 */ public void inOrder() { inOrder(root); } public void inOrder(TreeNode localRoot) { if (localRoot != null) { inOrder(localRoot.left); System.out.print(localRoot.data + " "); inOrder(localRoot.right); } } /** * 先序遍历 */ public void preOrder() { preOrder(root); } public void preOrder(TreeNode localRoot) { if (localRoot != null) { System.out.print(localRoot.data + " "); preOrder(localRoot.left); preOrder(localRoot.right); } } /** * 后序遍历 */ public void postOrder() { postOrder(root); } public void postOrder(TreeNode localRoot) { if (localRoot != null) { postOrder(localRoot.left); postOrder(localRoot.right); System.out.print(localRoot.data + " "); } } }
输出结果:
中序遍历:1 2 3 4 5 6 7 7 8 9
先序遍历:2 1 8 7 4 3 6 5 7 9
后序遍历:1 3 5 6 4 7 7 9 8 2
相关文章推荐
- position
- swing 单选框(互斥buttonGroup),设置默认值,获取值
- 黑马程序员-OC回顾-基础语法(二)
- c总结8 --- 二级指针使用三种模型之一(二级指针1)
- 关于java POI读取Excel2007流关不掉问题
- webview简单使用
- 单链表之检测链表是否有环并找出环的入口点
- fatal error C1083: Cannot open type library file: 'swpublished.tlb': No such file or directory 解决办法
- swing 填充表格(自动)
- eclipse 工程测试包
- Dubbo client can not supported string message
- 批量地导入本地的scholar.enw到endnote
- 10.21html 标签
- 判断一个小时之内是否重复发送了10次短信
- MQ中 amqsput : command not found的解决办法
- 内部api请求
- Android 如何直播RTMP流
- 打造高性能JAVA应用你需要知道的
- SkipList跳表基本原理
- swing 确认框和提示框