父节点表示法是让每个节点记住它的父节点的索引,子节点链是让父节点记住它的所有子节点。
package com.answer.binaryTree;
import java.util.ArrayList;
import java.util.List;
public class TreeChild {
private static class SonNode{
private int pos;
private SonNode next;
public SonNode(int pos,SonNode next){
this.pos=pos;
this.next=next;
}
}
private static class Node{
private String data;
private SonNode first;
public Node(String data){
this.data=data;
this.first=null;
}
}
private int DEFAULT_SIZE=16;
private int treeSize=0;
private Node[] nodes;
private int nodeNum;
public TreeChild(String data){
this.treeSize=DEFAULT_SIZE;
nodes=new Node[treeSize];
nodes[0]=new Node(data);
nodeNum++;
}
public TreeChild(String data,int size){
this.treeSize=size;
nodes=new Node[treeSize];
nodes[0]=new Node(data);
nodeNum++;
}
public void add(String data,Node parent){//向指定节点添加子节点
for(int i=0;i<treeSize;i++){
if(nodes[i]==null){
nodes[i]=new Node(data);
//添加到子节点链中
if(parent.first==null){
parent.first=new SonNode(i,null);
}else {
SonNode sonNode=parent.first;
while(sonNode.next!=null){
sonNode=sonNode.next;
}
sonNode.next=new SonNode(i,null);
}nodeNum++;
return;
}
}
}
public boolean empty(){
return nodes[0]==null;
}
public Node root(){
return nodes[0];
}
public List<Node> getChild(Node parent){
List<Node> list=new ArrayList<>();
SonNode fir=parent.first;
while(fir!=null){
list.add(nodes[fir.pos]);
fir=fir.next;
}return list;
}
public Node child(Node parent,int index){//返回指定父节点的子节点
SonNode fir=parent.first;
for(int i=0;fir!=null;i++){
if(i==index){
return nodes[fir.pos];
}
fir=fir.next;
}return null;
}
public int deep(){
return deep(root());
}
private int deep(Node node) {
if(node.first==null){
return 1;
}else {
int max=0;
SonNode fir=node.first;
while(fir!=null){
int temp=deep(nodes[fir.pos]);
if(temp>max){
max=temp;
}
fir=fir.next;
}return max+1;
}
}
public int pos(Node node){
for(int i=0;i<treeSize;i++){
if(nodes[i]==node){
return i;
}
}return -1;
}
public static void main(String[] args) {
TreeChild tree=new TreeChild("Root");
Node root=tree.root();
tree.add("A",root);
tree.add("B",root);
List<Node> list=tree.getChild(root);
for(Node node:list){
System.out.println(node.data);
}
tree.add("C",list.get(0));
System.out.println(tree.child(list.get(0),0).data);
System.out.println(tree.deep());
}
}