大体思路:
1.思路:
递归方法的输入一共4个
1.当前树,2.当前节点的值,3.当前递归到的树的层数,4.递归中到达过的最大层数(即整个树的最大高度)。
返回值:
树的最大高度
2.数据结构:
1.树使用HashMap<Integer,ArrayList>来代表,其中Integer代表树中节点的值,ArrayList代表节点对应的孩子节点。
2.使用ArrayList存储当前层的孩子节点。
3.代码:
dfs遍历方法:
public static int dfs(HashMap<Integer,ArrayList<Integer>> tree,int node,int curHeight,int maxHeight){
ArrayList<Integer> children = tree.get(node);
if(children == null){
return curHeight;
}
else{
for(int child:children){
maxHeight = dfs(tree,child,curHeight+1,curHeight+1);
}
}
return maxHeight;
}
主方法:
public static void main(String[] args) {
HashMap<Integer,ArrayList<Integer>> tree = new HashMap<Integer,ArrayList<Integer>>();
int[] ints1 = {2,3};
ArrayList<Integer> result1 = new ArrayList<Integer>();
for(int i:ints1) {
result1.add(i);
}
int[] ints2 = {4};
ArrayList<Integer> result2 = new ArrayList<Integer>();
for(int i:ints2) {
result2.add(i);
}
int[] ints3 = {5};
ArrayList<Integer> result3 = new ArrayList<Integer>();
for(int i:ints3) {
result3.add(i);
}
tree.put(1,result1);
tree.put(2, result2);
tree.put(4, result3);
dfs(tree,1,0,0);
}