栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

数据结构篇之第(五)幕——树的深度(Java实现)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构篇之第(五)幕——树的深度(Java实现)


main方法的开头,我先构造了一棵树,depth1()跟depth2()都是用了递归,depth3()借助了用queue实现的广度优先算法:

	
public class Depth {

    private static int maxDepth = 0;

    private static List depthAll = new ArrayList<>();

    public static void main(String[] args){
        BinaryTreeNode one = new BinaryTreeNode(10);

        BinaryTreeNode left = new BinaryTreeNode(5);
        left.setRight(new BinaryTreeNode(6));
        left.getRight().setRight(new BinaryTreeNode(8));
        one.setLeft(left);

        BinaryTreeNode right = new BinaryTreeNode(15);
        right.setLeft(new BinaryTreeNode(12));
        right.setRight(new BinaryTreeNode(18));
        one.setRight(right);

        depth1(one);
        int max = 0;
        for(int i = 0; i < depthAll.size(); i++){
            if(depthAll.get(i) > max){
                max = depthAll.get(i);
            }
        }
        System.out.println("depth1 result :" + max);
        System.out.println("depth2 result :" + depth2(one));
        System.out.println("depth3 result :" + depth3(one));
    }

    
    private static void depth1(BinaryTreeNode node){
        if(node == null){
            return;
        }
        maxDepth++;
        if(node.getLeft() != null || node.getRight() != null){
            depth1(node.getLeft());
            depth1(node.getRight());
        }else{
            System.out.println("leaf value: " + node.getValue());
            depthAll.add(maxDepth);
            maxDepth = 0;
        }
        return;
    }

    
    private static int depth2(BinaryTreeNode node){
        if(node == null){
            return 0;
        }
        return 1 + Math.max(depth2(node.getLeft()), depth2(node.getRight()));
    }

    
    private static int depth3(BinaryTreeNode node){
        Queue queue = new linkedList<>();
        queue.offer(node);
        BinaryTreeNode current;
        int level = 0;
        while(queue != null && queue.size() > 0){
            level++;
            int cur = 0;
            int last = queue.size();
            while(cur < last){
                current = queue.poll();
                if(current.getLeft() != null){
                    queue.offer(current.getLeft());
                }
                if(current.getRight() != null){
                    queue.offer(current.getRight());
                }
                cur++;
            }

        }
        return level;
    }
}

输出:

depth1 result :4
depth2 result :4
depth3 result :4
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/585197.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号