559. N 叉树的最大深度


559. N 叉树的最大深度

     public int maxDepth(Node root) {
        if (root == null) {
      return 0;
    } else if (root.children.isEmpty()) {
      return 1;
    } else {
      List<Integer> heights = new LinkedList<>();
      for (Node item : root.children) &#123;
        heights.add(maxDepth(item));
      &#125;
      return Collections.max(heights) + 1;
    &#125;
    public int maxDepth(Node root) &#123;
        Queue<Node> que=new LinkedList();
        int depth=0;
        if(root!=null)&#123;
            que.add(root);
        &#125;
        while(!que.isEmpty())&#123;
            int size=que.size();
            depth++;
            for(int i=0;i<size;i++)&#123;
                Node node=que.peek();
                que.poll();
                for(Node val:node.children)&#123;
                    if(val!=null)&#123;
                        que.add(val);
                    &#125;
                &#125;
            &#125;
        &#125;
        return depth;
    &#125;
public int maxDepth(Node root) &#123;
    Queue<Pair<Node, Integer>> stack = new LinkedList<>();
    if (root != null) &#123;
      stack.add(new Pair(root, 1));
    &#125;

    int depth = 0;
    while (!stack.isEmpty()) &#123;
      Pair<Node, Integer> current = stack.poll();
      root = current.getKey();
      int current_depth = current.getValue();
      if (root != null) &#123;
        depth = Math.max(depth, current_depth);
        for (Node c : root.children) &#123;
          stack.add(new Pair(c, current_depth + 1));
        &#125;
      &#125;
    &#125;
    return depth;
  &#125;

//作者:LeetCode
//链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/solution/ncha-shu-de-zui-da-shen-du-by-leetcode/
    public int maxDepth(Node root) &#123;
        if (null == root) &#123;
            return 0;
        &#125;
        int result = 1;
        for (Node child : root.children) &#123;
            result = Math.max(result, 1 + maxDepth(child));
        &#125;
        return result;
    &#125;

文章作者:   future
版权声明:   本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 future !
  目录