【Leetcode】559. Maximum Depth of N-ary Tree

题目地址:

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

求多叉树的高度。用分治法。

import java.util.List;

public class Solution {
    public int maxDepth(Node root) {
        if (root == null) {
            return 0;
        }
        
        int max = 0;
        if (root.children != null) {
            for (Node child : root.children) {
                max = Math.max(max, maxDepth(child));
            }
        }
        
        return max + 1;
    }
}

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

时间复杂度 O ( n ) O(n) ,空间复杂度 O ( h ) O(h) h h 为树的高度,也是递归栈深度。

发布了86 篇原创文章 · 获赞 0 · 访问量 1196

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/104035695
今日推荐