206、N叉树的最大深度

题目描述:
在这里插入图片描述
很明显使用的是递归来进行
我的代码:

class Solution {
   public int maxDepth(Node root) {
		
		int max = 0;
		if(root == null){
			return 0;
		}
		if(root.children.size() == 0){
			return 1;
		}
		List<Integer> res = new ArrayList<>();
		List<Node> ch = root.children;
		for (Node node : ch) {
			res.add(1 + getMaxDepth(node));
		}
       System.out.println(res.toString());
		for (Integer node : res) {
			max = node > max? node : max;
		}
		return max;
        
    }
	
	public int getMaxDepth(Node node){
		List<Integer> res = new ArrayList<>();
		if(node == null){
			return 0;
		}
		
		int max = 0;
		List<Node> ch = new ArrayList<>();
		ch = node.children;
        if(ch.size() == 0){
			return 1;
		}
		for (Node node1 : ch) {
			res.add(1 + getMaxDepth(node1));
		}
		for (Integer node2 : res) {
			max = node2 > max? node2 : max;
		}
		return max;
	}
	
}

我的那个代码有许多冗余的地方,因此可以考虑改进的。
排名靠前的代码

class Solution {
    int depth=0;
    public int maxDepth(Node root) {
        if(root==null)
            return 0;
        helper(root, 0);
        return depth+1;
    }

    public void helper(Node root, int level) {
        if(root==null)
            return;
        if(level>depth)
            depth=level;
        if(root!=null && root.children!=null && root.children.size()>0) {
            for(Node child : root.children) {
                helper(child, level+1);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值