需求:在jsp页面显示一个二叉树,数据存储在数据库以parentId 来模拟二叉树数据
解决方案:拿到数据库的数据,然后在map里面以二叉树的行+列号作为key来存储数据。jsp页面两层循环就可以显示出来了。
原理图:
import java.util.HashMap;
import java.util.Map;
public class Test {
private final static int total_layer = 4;
public static void main(String[] args) {
Map<Integer,Integer> layer_count = new HashMap<Integer,Integer>();
t(0, layer_count);
}
/**
* 遍历制定层数的二叉树
* @param current_layer 当前层数
* @param layer_count 当前层遍历的位置
*/
private static void t(int current_layer,Map<Integer,Integer> layer_count){
current_layer += 1;
if(current_layer <= total_layer){
for(int i=1;i<=2;i++){
//定位当前层已经遍历了第几次
if(layer_count.containsKey(current_layer)){
layer_count.put(current_layer, layer_count.get(current_layer)+1);
}else{
layer_count.put(current_layer, 1);
}
System.out.println(current_layer+"---"+layer_count.get(current_layer));
t(current_layer,layer_count);
}
}
}
}
这里面主要用到了java参数传递两种方式:
实参:Java的基本数据类型,如int,double等在函数的参数传递时,传递的是副本。String也属于这一范畴。
形参:而如果是对象,则传递的是引用。