gpt4 book ai didi

data-structures - 非二叉树高度

转载 作者:行者123 更新时间:2023-12-01 11:49:02 24 4
gpt4 key购买 nike

有没有办法找到不一定是二叉树的高度?有许多计算二叉树高度的算法,但没有一种算法适用于非二叉树。

最佳答案

是的,有。递归方法可能类似于:

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

关于data-structures - 非二叉树高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13476508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com