【算法练习】二叉树方法对数组进行排序
2013-02-16 21:56
537 查看
package com.ryan; class Node { // 定义左子树,右子树节点 private Node left; private Node right; private int data; // 需要存放的数据 public Node() { } // 通过构造函数初始化data public Node(int data) { this.data = data; } // 获取data public int getData() { return this.data; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } // 增加结点方法 public void addNode(Node newNode) { // 如果新加的数据小于当前节点数据放在左子树上 if (newNode.getData() < this.data) { // 如果左子树为空才放 if (this.left == null) { this.left = newNode; } else { // 如果不为空继续往下找 this.left.addNode(newNode); } } else { //新结果的数据大于当前节点数据放在右子树上 if (this.right == null) { this.right = newNode; } else { this.right.addNode(newNode); } } } // 打印结点 public void printNode() { if (this.left != null) { this.left.printNode(); } System.out.println(this.data); if (this.right != null) { this.right.printNode(); } } } class BinaryTree { private Node root; public void sort(int[] a) { for (int i = 0; i < a.length; i++) { // 遍历数组并实例化Node类 Node newNode = new Node(a[i]); if (this.root == null) { this.root = newNode; } else { this.root.addNode(newNode); } } } public void print() { if(this.root != null) { this.root.printNode(); } } } public class TestBinaryTree { public static void main(String[] args) { int[] a = new int[]{ 2, 6, 4, 1, 8, 3 }; BinaryTree bt = new BinaryTree(); bt.sort(a); bt.print(); } }
相关文章推荐
- 怎样编写一个程序,把一个有序整数数组放到二叉树中? 编写实现链表排序的一种算法。说明为什么你会选择用这样的方法?
- Java学习之数组1(1.数组的声明;2.元素为引用数据类型的数组;3.关于main方法里的String[] args;4.数组排序;5.数3退1 数组算法,(用数组模拟链表);6数组查找之二分法;7数组的拷贝)
- 写一个方法对任意引用数据类型数组进行排序(入门级慎看,很难!!!)
- vue 根据数组中某一项的值进行排序的方法
- js sort方法根据数组中对象的某一个属性值进行排序
- sort() 方法用于对数组的元素进行排序
- js sort方法根据数组中对象的某一个属性值进行排序
- 对数组中的对象进行升序以及降序的排序方法(其中对象类型是系统类型).
- JAVA中对一维数组排序的方法(在快速排序上进行的优化)
- 使用Array的Sort()方法对数组进行排序
- 使用sort方法对数组进行排序(split()出现错误的解决)
- C#使用自定义算法对数组进行反转操作的方法
- 数组排序问题的两种方法:插入排序算法和递归(分治)算法
- php根据某字段对多维数组进行排序的方法
- 对字符串数组进行排序,在冒泡法排序中使用compareTo()方法确定排序的顺序。
- 那些年我们刷过的算法题(排序)---有一个只由0,1,2三种元素构成的整数数组,请使用交换、原地排序而不是使用计数进行排序
- JavaScript 使用 sort() 方法从数值上对数组进行排序
- [ActionScript 3.0] 对数组中的元素进行排序Array.sort()的方法
- 排序例子2:使用sort()方法对数组进行排序
- 一月十日练习习题,1数组数据存入字典并输出2降序 和倒叙 输出数组中内容3对字符串当中信息进行查找是否存在4 把数组当中信息按照中文排序