生成二叉排序树并先序遍历、中序遍历、后序遍历
2015-07-08 11:12
246 查看
1、新建BinaryTree.java文件定义二叉树结构:
2、新建操作类BinaryTreePreorder.java,插入方法:
3、遍历方法:
4、测试
测试结果:
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; } public int getData() { return data; } public void setData(int data) { this.data = data; } public BinaryTree getLeft() { return left; } public void setLeft(BinaryTree left) { this.left = left; } public BinaryTree getRight() { return right; } public void setRight(BinaryTree right) { this.right = right; } }
2、新建操作类BinaryTreePreorder.java,插入方法:
public static void insert(BinaryTree root, int data){ if(data > root.getData()){ if(root.getRight() == null){ root.setRight(new BinaryTree(data)); }else{ insert(root.getRight(), data); } }else{ if(root.getLeft() == null){ root.setLeft(new BinaryTree(data)); }else{ insert(root.getLeft(), data); } } }
3、遍历方法:
/** * 先序遍历 * @param root */ public static void preOrder(BinaryTree root){ if(root == null){ return; } //遍历出数据 System.out.print(root.getData() + "-"); if(root.getLeft() != null){ preOrder(root.getLeft()); } if(root.getRight() != null){ preOrder(root.getRight()); } } /** * 中序遍历 * @param root */ public static void inOrder(BinaryTree root){ if(root == null){ return; } if(root.getLeft() != null){ preOrder(root.getLeft()); } //遍历出数据 System.out.print(root.getData() + "-"); if(root.getRight() != null){ preOrder(root.getRight()); } } /** * 后序遍历 * @param root */ public static void suffixOrder(BinaryTree root){ if(root == null){ return; } if(root.getLeft() != null){ preOrder(root.getLeft()); } if(root.getRight() != null){ preOrder(root.getRight()); } //遍历出数据 System.out.print(root.getData() + "-"); }
4、测试
public static void main(String[] str) { int[] array = { 36, 10, 35, 66, 16, 18, 90, 76, 9, 20 }; BinaryTree root = new BinaryTree(array[0]); // 创建二叉树 for (int i = 1; i < array.length; i++) { insert(root, array[i]); // 向二叉树中插入数据 } System.out.println("先根遍历:"); preOrder(root); System.out.println(); System.out.println("中根遍历:"); inOrder(root); System.out.println(); System.out.println("后根遍历:"); suffixOrder(root); }
测试结果:
先根遍历: 36-10-9-35-16-18-20-66-90-76- 中根遍历: 10-9-35-16-18-20-36-66-90-76- 后根遍历: 10-9-35-16-18-20-66-90-76-36-
相关文章推荐
- 每天小练笔7-坐标变换
- String to Integer (atoi)
- 【译】29个你必须知道的Linux命令
- LeetCode90:Subsets II
- 自定义注解,核心逻辑代码--原创
- 自定义单点登录(2)
- MTK+高通方案商
- 调整home和根分区大小
- 最新版SDWebImage的使用
- 基于注解的SpringMVC简单介绍
- 应用 Command 模式进行流水号管理的最佳实践
- Android音频介绍
- leetCode 30.Substring with Concatenation of All Words (words中所有子串相连) 解题思路和方法
- char* 指向内容不能修改的问题(整理)
- MTK+高通方案商
- php-redis中的sort排序函数总结
- 2012年5月SAT香港真题解析
- 深入理解Intent和IntentFiler(一)
- 创建html文档——html的文档元素和元数据元素
- libevent参考手册第九章:连接监听器:接受TCP连接 (十一)