【LeetCode】559. N叉树的最大深度(Java)

给定一个 N 叉树,找到其最大深度。

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

例如,给定一个 3叉树 :
在这里插入图片描述
我们应返回其最大深度,3。

说明:

  1. 树的深度不会超过 1000。
  2. 树的节点总不会超过 5000。

解法一

bfs,使用队列

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public int maxDepth(Node root) {
        //特判
        if (root == null)   return 0;

        //bfs
        //队列
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        int depth = 0;
        while (!queue.isEmpty()) {
            //每次循环深度加1
            depth++;
            //每次循环遍历上一层保存的所有节点
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                //把节点的所有子节点放到队列中
                Node node = queue.poll();
                queue.addAll(node.children);
            }
        }
        return depth;
    }
}

在这里插入图片描述
可能是因为队列的增删操作,执行时间差了些。

解法二

dfs,使用递归

class Solution {
    public int maxDepth(Node root) {
		//dfs
		//递归
        return dfs(root, 1);
    }

    //递归
    private int dfs(Node node, int depth) {
	    //出口
        if (node == null)   return depth - 1;
		
		//递归当前节点的所有子节点
		//max为当前节点的最大深度
        int max = depth;
        for (int i = 0; i < node.children.size(); i++) {
        	//保存子节点返回的最大深度
            int d = dfs(node.children.get(i), depth + 1);
            if (d > max) {
                max = d;
            }
        }
        return max;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值