/**
* 二叉树结点
*/
public class Node {
private int data;
private Node leftChild;
private Node rigthChild;
public Node(){
}
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftChild() {
return leftChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getRigthChild() {
return rigthChild;
}
public void setRigthChild(Node rigthChild) {
this.rigthChild = rigthChild;
}
}
package mr.yang.testBtree;
/**
* 二叉树
*/
public class BinaryTree {
private Node root;
public BinaryTree() {
}
public BinaryTree(int val) {
Node node = new Node(val);
this.root = node;
}
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
/**
* 二叉排序树添加
*/
public void add(int val) {
Node node = new Node(val);
if (root == null) {
this.root = new Node(val);
} else {
Node current = root;
while (true) {
if (val < current.getData()){//当前结点与根比较
//左边
if(current.getLeftChild()!=null){
//非空
current = current.getLeftChild();
}else {
//空
current.setLeftChild(node);
break;
}
}else{
//右边
if(current.getRigthChild()!=null){
//非空
current = current.getRigthChild();
}else {
//空
current.setRigthChild(node);
break;
}
}
}
}
}
/**
* 查找值并反返回结点
* @param val
* @return
*/
public Node get(int val){
Node currentNode = root;
while (true){
if(val == currentNode.getData()) {
return currentNode;
}else if(val>currentNode.getData()){
//右边
if(currentNode.getRigthChild() == null) return null;
currentNode = currentNode.getRigthChild();
}else {
//左边
if(currentNode.getLeftChild() == null) return null;
currentNode = currentNode.getLeftChild();
}
}
}
/**
* 中序遍历 左根右
*/
public void oder(Node node){
if(node == null) return;
oder(node.getLeftChild());
System.out.println(node.getData());
oder(node.getRigthChild());
}
}
测试代码:
package mr.yang.testBtree;
public class TestBinaryTree {
public static void main(String[] args) {
int a[] = {3,1,0,2,7,5,8,9};
BinaryTree bt = new BinaryTree();
for (int i = 0; i < a.length; i++) {
int val = a[i];
bt.add(val);
}
Node node = bt.get(8);
System.out.println(node.getData());
System.out.println(node.getLeftChild());
System.out.println(node.getRigthChild().getData());
/* Node node1 = bt.get(5);
System.out.println(node1.getData());
System.out.println(node1.getLeftChild());
System.out.println(node1.getRigthChild());*/
bt.oder(bt.getRoot());
}
}
分析:
每一个结点,有左孩子,数据,,右孩子
树由结点组成。将比根结点大的放右边,将比根结点小的放在边。
遍历:左根右。。。.
1.先遍历左孩子,若为空,则返回。否则递归遍历左孩子
2.输出中序
3遍历右孩子,若为空,则返回。否则递归遍历右孩子