二叉树代码
先展示二叉树的代码,此处的二叉树实现通过前序遍历加上补空的字符串来实现二叉树,具体代码如下:
public class Tree {
TreeNode root=null;
class TreeNode<T>{
//自定义二叉树结点类
T value;
TreeNode left;
TreeNode right;
TreeNode(T value){
this.value=value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
class Index{
//使遍历中i的值随递归改变
private int index;
public Index()
{
index = 0;
}
public Index(int x)
{
index = x;
}
int GetIndex() {
return index;}
void Inc() {
index+=1;}
}
public TreeNode createNode(String str,Index i){
//创建二叉树
TreeNode s=null;
if(str.charAt(i.GetIndex())!='#'){
s=new TreeNode(str.charAt(i.GetIndex()));
i.Inc();
s.setLeft(createNode(str,i));
i.Inc();
s.setRight(createNode(str,i));
}
return s;
}
public void CreateTree(String str){
//创建二叉树
Index i=new Index