二叉树节点类
import android.support.annotation.NonNull;
import java.util.ArrayList;
public class Note {
private static final String TAG = "Note.class";
int data;
Note leftChild;
Note rightChild;
Note parent;
/**
* 中序遍历
* @param note
*/
public static void LDR(Note note, ArrayList<Note> arrs) {
if (note == null) {
return;
}
LDR(note.leftChild, arrs);
arrs.add(note);
LDR(note.rightChild, arrs);
}
public Note(int data) {
this.data = data;
}
@NonNull
private Note getNewChildNote(int data) {
Note newNote = new Note(data);
newNote.parent = this;
return newNote;
}
/**
* 添加左节点
* @param data
*/
public void addLeftChild(int data) {
addLeftChild(getNewChildNote(data));
}
/**
* 添加左节点
* @param note
*/
public void addLeftChild(Note note) {
if (note == null) {
return;
}
if (leftChild == null) {
leftChild = note;
} else {
leftChild.addNote(note);
}
}
/**
* 添加右节点
* @param data
*/
public void addRightChild(int data) {
addRightChild(getNewChildNote(data));
}
/**
* 添加右节点
* @param note
*/
public void addRightChild(Note note) {
if (note == null) {
return;
}
if (rightChild == null) {
rightChild = note;
} else {
rightChild.addNote(note);
}
}
/**
* 添加节点
* @param data
*/
public void addNote(int data) {
if (data > this.data) {
addRightChild(data);
} else {
addLeftChild(data);
}
}
/**
* 添加节点
* @param note
*/
public void addNote(Note note) {
if (note == null) {
return;
}
addNote(note.data);
}
/**
* 获取最左节点
* @return
*/
public Note getLastLeftChild() {
Note lastNote = this;
while (lastNote.leftChild != null) {
lastNote = lastNote.leftChild;
}
return lastNote;
}
/**
* 获取最右节点
* @return
*/
public Note getLastRightChild() {
Note lastNote = this;
while (lastNote.rightChild != null) {
lastNote = lastNote.rightChild;
}
return lastNote;
}
/**
* 查找子节点
* @param data
* @param list
*/
public void getChildNote(int data, ArrayList<Note> list) {
if (data == this.data) {
list.add(this);
}
if (data > this.data) {
if (rightChild != null) { rightChild.getChildNote(data, list); }
} else {
if (leftChild != null) { leftChild.getChildNote(data, list); }
}
}
/**
* 删除结点
*
*<p>1、如果被删除的结点p有左子树z1,找到其左子树z1的最右边的叶子结点r,用该叶子结点r的值来替代p的值,把r的左孩子作为r的父亲的右孩子。但是如果其左子树z1没有右叶子(或者说其左子树z1的最右叶子就是其左子树z1),则将左子树z1的指引指向左子树的左子树z2</p>
*<p>2、如果被删除的结点p没有左子树,直接用P的右孩子取代它。</p>
*
* @return
*/
public Note deleteNode()
{
if (leftChild != null) {
Note r = leftChild.getLastRightChild();
data = r.data;
if (r == leftChild) {
leftChild = r.leftChild;
} else {
r.parent.rightChild = r.leftChild;
}
return this;
} else {
return rightChild;
}
}
@Override
public String toString() {
String s = "Note:" + data;
if (leftChild != null) {
s += " Left:" + leftChild.data;
}
if (rightChild != null) {
s += " Right: " + rightChild.data;
}
if (parent != null) {
s += " Parent:" + parent.data;
}
return s;
}
}