二叉树
来源:互联网 发布:最新机顶盒软件排行 编辑:程序博客网 时间:2024/06/05 20:47
package class1;
class BinaryTree {
class Node {
private Comparable data ;
private Node left ;
private Node right ;
public void addNode(Node newNode) {
if(newNode.data.compareTo(this.data) < 0) {
if (this.left == null) {
this.left = newNode;
} else {
this.left.addNode(newNode);
}
}
if(newNode.data.compareTo(this.data) >= 0) {
if (this.right == null) {
this.right = newNode ;
} else {
this.right.addNode(newNode);
}
}
}
public void printNode() {
if (this.left != null){
this.left.printNode();
}
System.out.print(this.data + "\t");
if(this.right != null) {
this.right.printNode();
}
}
}
private Node root;
public void add(Comparable data){
Node newNode = new Node() ;
newNode.data = data ;
if(root == null) {
root = newNode;
} else {
root.addNode(newNode);
}
}
public void print(){
this.root.printNode();
}
}
public class ComparableDemo03 {
public static void main(String args[]) {
BinaryTree bt = new BinaryTree() ;
bt.add(8);
bt.add(3);
bt.add(3);
bt.add(10);
bt.add(9);
bt.add(1);
bt.add(5);
bt.add(5);
System.out.println("排序之后的结果:") ;
bt.print();
}
}
class BinaryTree {
class Node {
private Comparable data ;
private Node left ;
private Node right ;
public void addNode(Node newNode) {
if(newNode.data.compareTo(this.data) < 0) {
if (this.left == null) {
this.left = newNode;
} else {
this.left.addNode(newNode);
}
}
if(newNode.data.compareTo(this.data) >= 0) {
if (this.right == null) {
this.right = newNode ;
} else {
this.right.addNode(newNode);
}
}
}
public void printNode() {
if (this.left != null){
this.left.printNode();
}
System.out.print(this.data + "\t");
if(this.right != null) {
this.right.printNode();
}
}
}
private Node root;
public void add(Comparable data){
Node newNode = new Node() ;
newNode.data = data ;
if(root == null) {
root = newNode;
} else {
root.addNode(newNode);
}
}
public void print(){
this.root.printNode();
}
}
public class ComparableDemo03 {
public static void main(String args[]) {
BinaryTree bt = new BinaryTree() ;
bt.add(8);
bt.add(3);
bt.add(3);
bt.add(10);
bt.add(9);
bt.add(1);
bt.add(5);
bt.add(5);
System.out.println("排序之后的结果:") ;
bt.print();
}
}
阅读全文
0 0
- 二叉树、二叉堆
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- 二叉树
- C语言基础复习——结构体(1)
- 数据库(4)查询
- Python科学计算--NumPy的数组对象ndarray
- 使用web服务器写一个登陆注册的界面
- vim文本编辑工具
- 二叉树
- #HTTP协议学习# (一)request 和response 解析
- XListView简单上拉加载下拉刷新
- OJ系统里用BufferedReader提高效率
- centos6搭建简易bind服务器
- redis学习笔记[2] redis的初始使用
- Android开发之Git基础操作
- 子Div脱离文档流后怎么撑开父Div
- Idea中的调试技巧