Non-binary tree height

后端 未结 4 976
盖世英雄少女心
盖世英雄少女心 2021-01-14 11:21

Is there a way to find the height of a tree which is not necessarily binary? There are many algorithms for the height of a binary tree but none of them will work for a non-b

4条回答
  •  醉话见心
    2021-01-14 11:36

    Yes, there is. A recursive approach could be something like:

    public class TreeNode{
        private List> children = new ArrayList>();
        private T data = null;
    
        public TreeNode(T data){
            this.data = data;
        }       
    
        public List> getChildren(){
            return children;
        }   
    
        public void setChild(TreeNode children){
            this.children.add(children);
        }   
    
        public Integer getHeight(TreeNode root){
            if(root == null) return 0;
            Integer h=0;
    
            for(TreeNode n : root.getChildren()){
                h = Math.max(h, getHeight(n));
            }
            return h+1;
        }
    }
    

    Test:

    public static void main(String[] args){
        TreeNode root = new TreeNode(50);
        TreeNode c1 = new TreeNode(100);
        TreeNode c2= new TreeNode(10);
        TreeNode c3 = new TreeNode(-5);
        TreeNode c4 = new TreeNode(0);
        TreeNode c5 = new TreeNode(33);
        TreeNode c6 = new TreeNode(1);
        TreeNode c7 = new TreeNode(2);
        TreeNode c8 = new TreeNode(3);
        TreeNode c9 = new TreeNode(300);
        TreeNode c10 = new TreeNode(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));
    }
    

    Result:

    Heigth: 
    4
    

    EDIT: Returns 4, instead of 3 as stated earlier

提交回复
热议问题