leetcode 559. N叉樹的最大深度

給定一個 N 叉樹,找到其最大深度。

最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。

例如,給定一個 3叉樹 :

我們應返回其最大深度,3。

說明:

  1. 樹的深度不會超過 1000
  2. 樹的節點總不會超過 5000

dfs遞歸求深度

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    int maxValue = 0;
    
    public int maxDepth(Node root) {
        if(root == null){
            return 0;
        }
        int depth = 0;
        for(int i = 0;i < root.children.size();i++){
            depth = Math.max(depth,maxDepth(root.children.get(i)));
        }
        return depth + 1;
    }
}

層序遍歷求深度

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    int maxValue = 0;
    
    public int maxDepth(Node root) {
        if(root == null){
            return 0;
        }
        if(root.children.size() == 0){
            return 1;
        }
        int depth = 0;
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while(queue.size()!=0){
            depth++;
            int count = queue.size();
            for(int i = 0;i < count;i++){
                Node node = queue.poll();
                if(node.children.size() != 0){
                    queue.addAll(node.children);
                }
            }
            
        }
        return depth;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章