二叉排序树的实现
来源:互联网 发布:apache服务器搭建 编辑:程序博客网 时间:2024/06/06 00:32
问题表述:
二叉排序树,如果左子树不为空,那么左子树上所有节点的值均小于其根结点的值;如果右子树不为空,那么右子树所有节点的值均大于其根结点的值;左右子树也分别为二叉排序树。
代码实现:
class Node{ public int data; public Node left; public Node right; public Node(int data){ this.data = data; this.left = null; this.right = null; }}public class BinaryTree { private Node root; public BinaryTree(){ root = null; } //insert public void insert(int data) { Node newnode = new Node(data); if (root==null) { root = newnode; }else { Node current = root; Node parent; while (true) { parent = current; if (data<current.data) { current = current.left; if (current==null) { parent.left = newnode; return; } }else { current = current.right; if (current==null) { parent.right = newnode; return; } } } } } //build public void buildTree(int[] data) { for (int i = 0; i < data.length; i++) { insert(data[i]); } } //inOrder public void inOrder(Node localRoot) { if (localRoot!=null) { inOrder(localRoot.left); System.out.print(localRoot.data+" "); inOrder(localRoot.right); } } public void inOder() { inOrder(this.root); } //preOrder public void preOrder(Node localRoot) { if (localRoot!=null) { System.out.print(localRoot.data+" "); preOrder(localRoot.left); preOrder(localRoot.right); } } private void preOrder() { preOrder(this.root); } //postOrder public void postOrder(Node localRoot) { if (localRoot!=null) { postOrder(localRoot.left); postOrder(localRoot.right); System.out.print(localRoot.data+" "); } } public void postOrder() { postOrder(this.root); } public static void main(String[] args) { BinaryTree binaryTree = new BinaryTree(); int[] data = {2,8,7,4,9,3,1,6,7,5}; binaryTree.buildTree(data); System.out.print("inOrder is: "); binaryTree.inOder(); System.out.println(); System.out.print("preOrder is: "); binaryTree.preOrder(); System.out.println(); System.out.print("postOrder is: "); binaryTree.postOrder(); System.out.println(); }}
运行结果:
inOrder is: 1 2 3 4 5 6 7 7 8 9
preOrder is: 2 1 8 7 4 3 6 5 7 9
postOrder is: 1 3 5 6 4 7 7 9 8 2
0 0
- 二叉排序树的实现
- 二叉排序树的简单实现
- 二叉排序树的实现
- 二叉排序树的实现
- 二叉排序树的实现
- 二叉排序树的实现
- 二叉排序树的简单实现
- 简单实现的二叉排序树
- 二叉排序树的简单实现
- 二叉排序树的实现
- 数据结构 - 二叉排序树的实现
- 二叉排序树的完整实现
- 二叉排序树的C++实现
- 二叉排序树的实现
- 二叉排序树的实现
- 二叉排序树的java实现
- 二叉排序树的实现
- 二叉排序树的实现
- python升级2.6.6-->2.7.3引起的pip和easy_install执行错误
- Bootstrap警告面板
- 动效神器 Origami Studio 汉化
- Spring Boot 运行原理
- Android CardView 和Material Design风格设计学习
- 二叉排序树的实现
- Android 利用layoutParams代码动态布局空间位置
- 字符串匹配-KMP
- 华为手机logcat不出日志解决方案
- Ubuntu
- Linux安装apache详解
- javascript第5章
- View页面间的跳转
- 解决Android Studio编译后安装apk报错:The APK file does not exist on disk