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);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/89062185
今日推荐