有没有一种方法可以找到不一定是二进制的树的高度?对于二叉树的高度,有很多算法,但是对于非二叉树,它们都不起作用。
最佳答案
就在这里。递归方法可能类似于:
public class TreeNode<T>{
private List<TreeNode<T>> children = new ArrayList<TreeNode<T>>();
private T data = null;
public TreeNode(T data){
this.data = data;
}
public List<TreeNode<T>> getChildren(){
return children;
}
public void setChild(TreeNode<T> children){
this.children.add(children);
}
public Integer getHeight(TreeNode<T> root){
if(root == null) return 0;
Integer h=0;
for(TreeNode<T> n : root.getChildren()){
h = Math.max(h, getHeight(n));
}
return h+1;
}
}
测试:
public static void main(String[] args){
TreeNode<Integer> root = new TreeNode<Integer>(50);
TreeNode<Integer> c1 = new TreeNode<Integer>(100);
TreeNode<Integer> c2= new TreeNode<Integer>(10);
TreeNode<Integer> c3 = new TreeNode<Integer>(-5);
TreeNode<Integer> c4 = new TreeNode<Integer>(0);
TreeNode<Integer> c5 = new TreeNode<Integer>(33);
TreeNode<Integer> c6 = new TreeNode<Integer>(1);
TreeNode<Integer> c7 = new TreeNode<Integer>(2);
TreeNode<Integer> c8 = new TreeNode<Integer>(3);
TreeNode<Integer> c9 = new TreeNode<Integer>(300);
TreeNode<Integer> c10 = new TreeNode<Integer>(350);
root.setChild(c1);
root.setChild(c2);
c2.setChild(c3);
c3.setChild(c4);
c3.setChild(c5);
c3.setChild(c6);
c3.setChild(c7);
c3.setChild(c8);
c1.setChild(c9);
c1.setChild(c10);
System.out.print("Pre order: \n");
root.dfs(root, 0);
System.out.print("\nPost order: \n");
root.dfs(root, 1);
System.out.print("\nBFS: \n");
root.bfs(root);
System.out.println();
System.out.print("\nHeigth: \n");
System.out.println(root.getHeight(root));
}
结果:
Heigth:
4
编辑:返回4,而不是3如前所述