二叉树的定义:
二叉树的每个结点至多只有二棵子树(不存在度大于2的结点),二叉树的子树有左右之分,次序不能颠倒。二叉树的第i层至多有2i-1个结点;深度为k的二叉树至多有2k-1个结点;对任何一棵二叉树T,如果其终端结点数为n0,度为2的结点数为n2,则n0=n2+1。
二叉树的示例:
二叉树的java实现:
每个节点的node实现:
public class Node {
private int data;
private Node leftNode;
private Node rightNode;
@Override
public String toString() {
return "Node{" +
"data=" + data +
", leftNode=" + leftNode +
", rightNode=" + rightNode +
'}';
}
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public Node getRightNode() {
return rightNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
}
树的实现:
public class Tree {
private Node rootNode;
/**
* 插入操作
* 死循环找到插入的位置。
* @param data
*/
public void insert(int data){
Node newNode = new Node(data);
//指向当前节点
Node currentNode=rootNode;
//指向当前节点的父节点
Node parentNode;
if (currentNode==null){
rootNode=newNode;
return;
}else{
while (true){
parentNode=currentNode;
if (data>=currentNode.getData()){
currentNode=currentNode.getRightNode();
if (currentNode==null){
currentNode=newNode;
parentNode.setRightNode(currentNode);
return;
}
}else if (data<currentNode.getData()){
currentNode=currentNode.getLeftNode();
if (currentNode==null){
currentNode=newNode;
parentNode.setLeftNode(currentNode);
return;
}
}
}
}
}
/**
* 查找节点
* @param value
* @return
*/
public Node find(int value){
//指向当前节点
Node currentNode=rootNode;
//当要找的数不是当前节点时就一直循环
while(currentNode.getData()!=value){
if (value>currentNode.getData()){
currentNode=currentNode.getRightNode();
}else {
currentNode=currentNode.getLeftNode();
}
if (currentNode==null){
return null;
}
}
return currentNode;
}
public Node getRootNode() {
return rootNode;
}
}
测试:
public class TreeTest {
public static void main(String[] args) {
Tree tree = new Tree();
tree.insert(12);
tree.insert(15);
tree.insert(2);
tree.insert(13);
tree.insert(13);
System.out.println(tree.getRootNode().getData());
System.out.println(tree.getRootNode().getRightNode().getData());
System.out.println(tree.getRootNode().getLeftNode().getData());
System.out.println(tree.getRootNode().getRightNode().getLeftNode().getData());
System.out.println(tree.getRootNode().getRightNode().getLeftNode().getRightNode().getData());
System.out.println("-------------------------------");
System.out.println(tree.find(15));
System.out.println(tree.find(13));
System.out.println(tree.find(2));
System.out.println(tree.find(12));
}
}