二叉链表存储二叉树,简单说就是:添加左右两个子节点,分别代表两个引用,left, right,来记住该节点的左右子节点。
源代码如下(blog中所以源代码均已实际运行通过):
/*
* a simple example to TwoBinTree
* HanChun 2015.6.7
*/
package mywork.c20150607;
public class TwoLinkBinTreeDemo<T> {
public class TreeNode{
TreeNode left;
TreeNode right;
Object data;
public TreeNode(){
}
public TreeNode(T data){
this.data = data;
}
public TreeNode(T data, TreeNode left, TreeNode right){
this.data = data;
this.left = left;
this.right = right;
}
}
TreeNode root; //二叉树的根节点
public TwoLinkBinTreeDemo(){
this.root = new TreeNode();
}
public TwoLinkBinTreeDemo(T data){
this.root = new TreeNode(data);
}
/**
* 为指定节点添加新的节点
* @param parent 需要添加新节点的节点
* @param data 新节点数据
* @param isLeft 需添加 的父节点是不是左节点
* @return 新增加的节点
*/
public TreeNode addNode(TreeNode parent, T data, boolean isLeft){
if(parent == null){
throw new RuntimeException("节点为空,不能添加新节点");
}
if(isLeft && parent.left != null){
throw new RuntimeException("左节点已有元素,不能添加新节点");
}
if(!isLeft && parent.right != null){
throw new RuntimeException("右节点已有元素,不能添加新节点");
}
TreeNode newNode = new TreeNode(data);
if(isLeft){
parent.left = newNode;
}else{
parent.right = newNode;
}
return newNode;
}
//判断二叉树是否为空
public boolean isEmpty(){
return root.data == null;
}
//得到二叉树的根节点
public TreeNode getRoot(){
if(isEmpty()){
throw new RuntimeException("没有根节点");
}
return root;
}
//求二叉树的深度
public int deep(TreeNode node){
if(node == null){
return 0;
}
if(node.left == null && node.right == null){
return 1;
}else{
int leftDeep = deep(node.left); //这边有递归的思想,如果难以理解,可以看我的另一篇文章“递归 Java”;
int rightDeep = deep(node.right);
int max = leftDeep > rightDeep ? leftDeep : rightDeep;
return max + 1;
}
}
}