package com.foolfish.tree;
/**
* @desc 二叉树算法
* @author foolfish.chen
*
*/
public class BinaryTree {
private int nodeValue = 0; // 当前节点值
private BinaryTree lChild = null;// 左孩子节点
private BinaryTree rChild = null;// 右孩子节点
public BinaryTree(int node,BinaryTree l, BinaryTree r){
this.nodeValue = node;
this.lChild = l;
this.rChild = r;
}
/**
* @return the nodeValue
*/
public int getNodeValue() {
return nodeValue;
}
/**
* @param nodeValue the nodeValue to set
*/
public void setNodeValue(int nodeValue) {
this.nodeValue = nodeValue;
}
/**
* @return the lChild
*/
public BinaryTree getLChild() {
return lChild;
}
/**
* @param child the lChild to set
*/
public void setLChild(BinaryTree child) {
lChild = child;
}
/**
* @return the rChild
*/
public BinaryTree getRChild() {
return rChild;
}
/**
* @param child the rChild to set
*/
public void setRChild(BinaryTree child) {
rChild = child;
}
/**
* @desc 构造二叉树
* @param node
* @param nodeValue
*/
public void createTree(BinaryTree node,int nodeValue){
/*********************************
* 判断当前值是否小于当前节点,若小于当前
* 节点,继续往左子树遍历,直到遍历到叶子
* 节点,又子树同理
*********************************/
if(node.getNodeValue()>nodeValue){
if(node.getLChild() != null){
node.createTree(node.lChild, nodeValue);
}else{
node.setLChild(new BinaryTree(nodeValue,null,null));
}
}else{
if(node.getRChild() != null){
node.createTree(node.rChild, nodeValue);
}else{
node.setRChild(new BinaryTree(nodeValue,null,null));
}
}
}
/**
* @desc 打印从指定节点开始的树结构
* @param node
*/
public void printAll(BinaryTree node){
// 从左边开始遍历
if(node.getLChild() != null){
printAll(node.getLChild());
}
System.out.print(node.getNodeValue()+",");
// 从左边开始遍历
if(node.getRChild() != null){
printAll(node.getRChild());
}
}
/**
* @desc 查找指定直
* @param node 节点信息
* @param Value 需要查找的值
*/
public int search(BinaryTree node,int Value){
int returnValue = 0;
/******************************
* 若当前节点大于要查找的值,查找左树
* 若当前节点小于要查找的值,查找右树
* 若当前节点等于要查找的值,放回当前值
******************************/
if(node.getNodeValue()>Value){
returnValue = search(node.getLChild(), Value);
}else if(node.getNodeValue()<Value){
returnValue = search(node.getRChild(), Value);
}else{
return node.getNodeValue();
}
return returnValue;
}
/**
* @desc main App
* @param args
*/
public static void main(String[] args){
int[] array = {14,3,67,23,1,7,8,25,78,11,46,9};
BinaryTree btree = new BinaryTree(array[0],null,null);
for(int i = 1 ; i<array.length ; i++){
btree.createTree(btree, array[i]);
}
/*********************************
* 打印排序后的值
*********************************/
btree.printAll(btree);
/*********************************
* 查找指定值
*********************************/
System.out.println();
System.out.println(btree.search(btree, 3));
}
}