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

来源:互联网 发布:c语言环境变量设置 编辑:程序博客网 时间:2024/06/08 20:01
package com.ryan;class Node {// 定义左子树,右子树节点private Node left;private Node right;private int data; // 需要存放的数据public Node() {}// 通过构造函数初始化datapublic Node(int data) {this.data = data;}// 获取datapublic 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();}}

原创粉丝点击