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

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();
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值