二叉排序树的实现与基本操作二叉排序树的实现与基本操作
二叉排序树又称二叉查找树。本文主要对二叉排序树的实现与基本操作进行详细介绍,以下代码实现了:1、二
叉树的构建;2、二叉树的中、前、后、层序遍历;3、二叉树中结点的最大距离。下面就跟着小编一起来看下
吧
二叉排序树又称二叉查找树。它或者是一颗空树,或者是具有以下性质的二叉树:二叉排序树又称二叉查找树。它或者是一颗空树,或者是具有以下性质的二叉树:
①如果左子树不空,那么左子树上所有结点的值均小于它的根结点的值;
②如果右子树不空,那么右子树上所有结点的值均大于它的根结点的值;
③左右子树也分别为二叉排序树。
以下代码实现了:以下代码实现了:
二叉树的构建
二叉树的中、前、后、层序遍历
二叉树中结点的最大距离
import java.util.LinkedList;
import java.util.Queue;
class Node{
public int data;
public Node left;
public Node right;
public int leftMaxDistance;
public int rightMaxDistance;
public Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
/**
* @author TY
* 实现二叉排序树,包括插入、中序遍历、先序遍历、后序遍历、计算所有节点的最大距离的功能
*/
public class BinaryTree {
private Node root;
public BinaryTree(){
root=null;
}
public void insert(int data){
Node newNode=new Node(data);
if(root==null)
root=newNode;
else{
Node current=root;
Node parent;
while (true) {//寻找插入位置
parent=current;
if(data<current.data){
current=current.left;
if(current==null){
parent.left=newNode;
return;
}
}else{
current=current.right;
if (current==null) {
parent.right=newNode;
return;
}
}
}
}
}
//将数值输入构建二叉树
public void buildTree(int[] data){
for (int i = 0; i < data.length; i++) {
insert(data[i]);
}
}
//中序遍历方法递归实现
public void inOrder(Node localRoot){
if(localRoot!=null){
评论0