您的位置:首页 > 其它

【算法练习】二叉树方法对数组进行排序

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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐