LeetCode每日刷题Day20---L559 N叉树的最大深度

L559 N叉树的最大深度

GitHub 账户:LuvnJoae  欢迎关注! https://github.com/LuvnJoae
GitHub 代码链接:https://github.com/LuvnJoae/Java_leetcode

思路与结果

在这里插入图片描述

代码思路1

package Day20_8_28.L559;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Node{
    public int val;
    public List<Node> children;

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

/**
 * 思路一
 1. 采用递归方式,类似寻找二叉树的最大深度
 2. 注意,和二叉树最大深度不同,多叉树的子树是通过List的形式进行存储的,所以在判断递归结束条件时,条件是List为空,而不是节点为null,节点为null只对应了给的root节点为null时的情况。
 反思
 1. 时间复杂度O(N),空间复杂度O(logN)(最优平衡时)
 2. 消耗资源过多,且递归占用的时间也很长。
 3. 对于List形式的多叉树的子树列表,判断是否为空,即没有子树,应该用方法.isEmpty()来判断,而不是==null的形式
 a. 两种判断方式的区别:https://blog.csdn.net/u011109881/article/details/50635247
 ii. 即:创建对象时就给了null值,则使用null判断
 iii. 新建一个对象,但是没有给值,则使用isEmpty判断(新建时给了初始对象,不是null)

 */
public class Solution {
    public int maxDepth(Node root){
        if (root == null){
            return 0;
        }else if (root.children.isEmpty()){
            return 1;
        }
        else {
            List<Integer> childCount = new ArrayList<>();
            for (int i = 0; i < root.children.size(); i++) {
                childCount.add(maxDepth(root.children.get(i)));
            }
            ;
            return Collections.max(childCount) + 1;
        }
    }
}

代码思路2

package Day20_8_28.L559;

import javafx.util.Pair;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 思路二
 1. 采用迭代的方法,通过通过队列或者栈的出入操作,模拟递归,并记录下每个节点对应的depth。
 反思
 1. 时间复杂度O(N),空间复杂度O(N)
 2. 也没有节省下多少的东西,空间复杂度反而更高了(理想条件下)

 */
public class Solutiuon2 {
    public int maxDepth(Node root){
        Queue<Pair<Node, Integer>> queue = new LinkedList<>();
        if (root != null){
            queue.add(new Pair(root, 1));
        }

        int depth = 0;
        while (!queue.isEmpty()){
            Pair<Node, Integer> currentNode = queue.poll();
            root = currentNode.getKey();
            depth = depth > currentNode.getValue() ? depth : currentNode.getValue();
            for (Node child : root.children) {
                queue.add(new Pair<>(child, currentNode.getValue()+1));
            }
        }
        return depth;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值