您的位置:首页 > 理论基础 > 数据结构算法

java数据结构 二叉树

2014-11-09 21:37 288 查看
有序数组:插入、删除数据项慢

链表:查找慢

树:查找、插入、删除都快

/*
* 二叉树结点
*/
public class Node {

//数据项
public long data;
public String sDate;
//左子结点
public Node leftChild;
//右子节点
public Node rightChild;
/*
* 构造方法
*/
public Node(long data,String sDate){
this.data=data;
this.sDate=sDate;
}
}
/*
* 二叉树
*/
public class Tree {
// 根节点
public Node root;
}


基本操作:
1、插入节点,按照二叉排序树插入

/*
* 插入节点
*/
public void insert(long value, String sValue) {
// 封装节点
Node newNode = new Node(value, sValue);
// 引用当前节点
Node cur = root;
// 引用父节点
Node parent;
// 第一次插入
if (root == null) {
root = newNode;
return;
} else {
while (true) {
// 父节点指向当前结点
parent = cur;
if (cur.data > value) {
cur = cur.leftChild;
if (cur == null) {
parent.leftChild = newNode;
return;
}
} else {
cur = cur.rightChild;
if (cur == null) {
parent.rightChild = newNode;
return;
}
}
}
}
}

2、查找节点
/*
* 查找节点
*/
public Node find(long value) {

Node cur = root;
while (cur.data != value) {
// 进行比较
if (cur.data > value)
cur = cur.leftChild;
else
cur = cur.rightChild;
if (cur == null)
return null;
}
return cur;
}

3、删除节点
(1)删除的是叶子节点

(2)删除的是含一个子节点的节点

(3)删除的是含两个子节点的节点(通过找到中序后继节点替换删除节点)

/*
* 删除节点
*/
public boolean delete(long value) {
// 引用当前节点
Node cur = root;
// 引用当前节点的父节点
Node parent=root;
boolean isLeftChild=true; //标记删除节点是否是父节点的左子节点
while (cur.data != value) {
parent = cur;
// 进行比较
if (cur.data > value){
cur = cur.leftChild;
isLeftChild=true;
}
else{
cur = cur.rightChild;
isLeftChild=false;
}
if (cur == null)
return false;
}
//删除叶子节点
if(cur.leftChild==null&& cur.rightChild==null){
if(cur==root)
root=null;
//如果是父节点的左子结点
else if(isLeftChild){
parent.leftChild=null;
}
else parent.rightChild=null;
}
//删除含有一个子节点的节点
else if(cur.rightChild==null){
if(cur==root)
root=cur.leftChild;
else if(isLeftChild){
parent.leftChild=cur.leftChild;
}
else
parent.rightChild=cur.leftChild;
}
else if(cur.leftChild==null){
if(cur==root)
root=cur.rightChild;
else if(isLeftChild)
parent.leftChild=cur.rightChild;
else
parent.rightChild=cur.rightChild;
}
//删除有两个子节点的节点
else{
Node successor=getSuccessor(cur); //返回中序后继节点
if(cur==root){
root=successor;
}
else if(isLeftChild){
parent.leftChild=successor;
}
else{
parent.rightChild=successor;
}
successor.leftChild=cur.leftChild;
}
return true;
}
/*
* 返回中序后继节点
*/
public Node getSuccessor(Node delNode){
Node successor=delNode;
Node successorParent=delNode;
Node cur=delNode.rightChild;
while(cur!=null){
successorParent=successor;
successor=cur;
cur=cur.leftChild;
}
if(successor!=delNode.rightChild){
successorParent.leftChild=successor.rightChild; //处理中序后继节点的父节点的左指针
successor.rightChild=delNode.rightChild; //处理中序后继节点的右节点
}
return successor;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息