1.定义节点
/**
* 定义节点
*/
public class BinaryTreeNode {
private BinaryTreeNode leftChild ; // 左子树
private BinaryTreeNode rightChild; // 右子树
private Integer date;
public BinaryTreeNode(){
}
public BinaryTreeNode(Integer date){
this(date,null,null);
}
public BinaryTreeNode(Integer date, BinaryTreeNode leftChild, BinaryTreeNode rightChild){
this.date = date;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
public BinaryTreeNode getLeftNode(){
return leftChild;
}
public void setLeftNode(BinaryTreeNode leftChild){
this.leftChild = leftChild;
}
public BinaryTreeNode getRightNode(){
return rightChild;
}
public void setRightNode(BinaryTreeNode rightChild){
this.rightChild = rightChild;
}
public Integer getDate(){
return date;
}
public void setDate(Integer date){
this.date = date;
}
}
2.生成(插入)二叉树
/**
* 实现二叉树
*/
public class BinaryTree {
/**
* 插入
*/
public static void insertNode(BinaryTreeNode node, Integer i){
// 根节点为空
if(node.getDate() == null){
node.setDate(i);
return;
}
// 小于根节点
if(node.getDate() > i){
// 左子树为空
if(node.getLeftNode() == null){
node.setLeftNode(new BinaryTreeNode(i));
}else {
insertNode(node.getLeftNode(),i);
}
}else { // 大于等于根节点
// 右子树为空
if(node.getRightNode() == null){
node.setRightNode(new BinaryTreeNode(i));
}else {
insertNode(node.getRightNode(),i);
}
}
}
}
3.遍历二叉树
/**
* 中序遍历
*/
public static void inOrder(BinaryTreeNode node) {
if (node != null) {
inOrder(node.getLeftNode());
System.out.print(node.getDate() + " ");
inOrder(node.getRightNode());
}
}
/**
* 前序遍历
*/
public static void preOrder(BinaryTreeNode node) {
if (node != null) {
afterOrder(node.getLeftNode());
afterOrder(node.getRightNode());
System.out.print(node.getDate() + " ");
}
}
/**
* 后序遍历
*/
public static void postOrder(BinaryTreeNode node) {
if (node != null) {
System.out.print(node.getDate() + " ");
beforeOrder(node.getLeftNode());
beforeOrder(node.getRightNode());
}
}
public static void main(String[] args) {
BinaryTreeNode binaryTreeNode = new BinaryTreeNode();
for(int i =0;i < 10; i++){
insertNode(binaryTreeNode,(int)(Math.random()*100));
}
System.out.println("中序遍历");
inOrder(binaryTreeNode);
}
4.查找
/**
* 递归查找
*/
public static boolean findNode(BinaryTreeNode node, Integer i){
if(node == null){
return false;
}
if(node.getDate() > i){
return findNode(node.getLeftNode(),i);
}
else if(node.getDate() < i){
return findNode(node.getRightNode(),i);
}
else{
return true;
}
}