java实现的二叉树排序

来源:互联网 发布:node 命令行多步执行 编辑:程序博客网 时间:2024/04/29 06:08

二叉树节点的特征:

1.当前树节点的值大于其左孩子节点值,当前树节点的值小于其右孩子节点值

2.左右孩子节点也符合1所述特点


package sort;


/**
 * 二叉树数据结构
 * created by tangsi 2014/09/14
 * @author Administrator
 * 
 */
public class BinaryNode {


/**
* 树节点所包裹的值
*/
private int value;


/**
* 左孩子
*/
private BinaryNode leftChild;


/**
* 右孩子
*/
private BinaryNode rightChild;


public BinaryNode(int value, BinaryNode leftChild, BinaryNode rightChild) {
super();
this.value = value;
this.leftChild = leftChild;
this.rightChild = rightChild;
}


/**
* 遍历二叉树
* @param root
*/
public static void iterate(BinaryNode root) {

if(root.getLeftChild() != null) {
iterate(root.getLeftChild());
}

System.out.print(root.getValue() +"\t");

if(root.getRightChild() != null) {
iterate(root.getRightChild());
}

}

/**
* 添加二叉树节点
* @param value
*/
public void addChild(int value) {
if(this.value > value) {  //添加为左孩子
if(this.leftChild != null) {
this.leftChild.addChild(value);
}else {
this.leftChild = new BinaryNode(value, null, null);
}
}else {  //添加为右孩子
if(this.rightChild != null) {
this.rightChild.addChild(value);
}else {
this.rightChild = new BinaryNode(value, null, null);
}
}
}


public int getValue() {
return value;
}


public void setValue(int value) {
this.value = value;
}


public BinaryNode getLeftChild() {
return leftChild;
}


public void setLeftChild(BinaryNode leftChild) {
this.leftChild = leftChild;
}


public BinaryNode getRightChild() {
return rightChild;
}


public void setRightChild(BinaryNode rightChild) {
this.rightChild = rightChild;
}

}



package sort;


import org.junit.Test;



/**
 * created by tangsi 2014/09/14
 * 二叉树排序测试
 * @author Administrator
 *
 */
public class BinaryTreeSortTest {


@Test
public void test1() {

int[] arr = new int[]{3,2,5,7,1,9,1};

BinaryNode root = new BinaryNode(arr[0], null, null);

for(int i=1;i <arr.length; i++) {
root.addChild(arr[i]);
}

BinaryNode.iterate(root);

}

}

0 0
原创粉丝点击