LeetCode 559: N 叉树的最大深度 Maximum Depth of N-ary Tree

题目:

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

Given a n-ary tree, find its maximum depth.

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

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

示例 1:


输入: root = [1,null,3,2,4,null,5,6]
输出: 3

示例 2:

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
输入: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出: 5

说明:

  1. 树的深度不会超过 1000

  2. 树的节点总不会超过 5000

Constraints:

  • The depth of the n-ary tree is less than or equal to 1000.

  • The total number of nodes is between [0, 10^4].

解题思路:

求 N 叉树深度明显就是考察其遍历算法:

  • 广度优先搜索(BFS):

    • 递归法

    • 迭代法

  • 深度优先搜索(DFS):

    • 递归法

    • 迭代法

  • 递归法思想

    • 自顶向下

    • 自底向上

具体可参考下文中的递归思想篇:

树的遍历    Traverse a Tree

以下仅展示两种算法的最优方法

DFS 递归法:

Java:

class Solution {
    int max = 0;
    public int maxDepth(Node root) {
        dfs(root, 1);
        return max;
    }
    private void dfs(Node n, int depth){ // DFS 函数
        if (n == null) // 基线条件
            return;
        max = Math.max(max, depth); // 取最大深度值
        for (Node c : n.children) // 递归子结点
            dfs(c, depth + 1); // depth 当前深度加一, depth 始终为当前结点的深度
    }
}

Python:

class Solution:
    def __init__(self):
        self.count = 0

    def maxDepth(self, root: 'Node') -> int:
        """
        :type root: Node
        :rtype: int
        """
        self.dfs(root, 1)
        return self.count

    def dfs(self, node: 'Node', depth):
        if not node: # 基线条件
            return
        self.count = max(depth, self.count) # 取最大深度值
        for cld in node.children: # 递归子结点
            self.dfs(cld, depth+1) # depth 当前深度加一, depth 始终为当前结点的深度

BFS 迭代法:

Java:

class Solution {
    public int maxDepth(Node root) {
        if(root == null)
            return 0;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root); //  根结点入队
        int depth = 0;
        while(!queue.isEmpty()){ //  队列不空,遍历不止
            int size = queue.size();
            for(int i = 0; i < size; i++){ // 遍历该层所有结点
                Node cur = queue.poll(); // 依次出队
                if(cur.children.size() != 0){
                    queue.addAll(cur.children); // 该结点的所有孩子结点入队
                }
            }
            depth++;
        }
        return depth;
    }
}

Python:

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        count = 0
        if not root:
            return count
        queue = collections.deque()  # 双端队列
        queue.append(root)  # 根结点入队
        while queue:  # 队列不空,遍历不止
            size = len(queue)  # 此时队列的大小就是该层所有结点总数
            tmp = list()
            while(size > 0):  # 遍历该层所有结点
                size -= 1
                node = queue.popleft()
                tmp.append(node.val)  # 依次出队
                for cld in node.children:  # 该层所有结点的孩子结点依次入队
                    queue.append(cld)
            count += 1 # 每层遍历结束, 深度加一
        return count

还有另一种递归解法, 可以一个 DFS 函数解题, 其思想类似 斐波那契数列 :

https://baike.baidu.com/item/斐波那契数列

该函数 DFS 求得每条路径上所有结点的深度, 取其中最大值:

Python

class Solution(object):
    def maxDepth(self, root):
        if root is None: 
            return 0 
        elif root.children == []:
            return 1
        else: 
            height = [self.maxDepth(c) for c in root.children] # 该路径上所有结点的深度
            return max(height) + 1 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值