559. N 叉树的最大深度

  1. public int maxDepth(Node root) {
  2. if (root == null) {
  3. return 0;
  4. } else if (root.children.isEmpty()) {
  5. return 1;
  6. } else {
  7. List<Integer> heights = new LinkedList<>();
  8. for (Node item : root.children) {
  9. heights.add(maxDepth(item));
  10. }
  11. return Collections.max(heights) + 1;
  12. }
  1. public int maxDepth(Node root) {
  2. Queue<Node> que=new LinkedList();
  3. int depth=0;
  4. if(root!=null){
  5. que.add(root);
  6. }
  7. while(!que.isEmpty()){
  8. int size=que.size();
  9. depth++;
  10. for(int i=0;i<size;i++){
  11. Node node=que.peek();
  12. que.poll();
  13. for(Node val:node.children){
  14. if(val!=null){
  15. que.add(val);
  16. }
  17. }
  18. }
  19. }
  20. return depth;
  21. }
  1. public int maxDepth(Node root) {
  2. Queue<Pair<Node, Integer>> stack = new LinkedList<>();
  3. if (root != null) {
  4. stack.add(new Pair(root, 1));
  5. }
  6. int depth = 0;
  7. while (!stack.isEmpty()) {
  8. Pair<Node, Integer> current = stack.poll();
  9. root = current.getKey();
  10. int current_depth = current.getValue();
  11. if (root != null) {
  12. depth = Math.max(depth, current_depth);
  13. for (Node c : root.children) {
  14. stack.add(new Pair(c, current_depth + 1));
  15. }
  16. }
  17. }
  18. return depth;
  19. }
  20. //作者:LeetCode
  21. //链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/solution/ncha-shu-de-zui-da-shen-du-by-leetcode/
  1. public int maxDepth(Node root) {
  2. if (null == root) {
  3. return 0;
  4. }
  5. int result = 1;
  6. for (Node child : root.children) {
  7. result = Math.max(result, 1 + maxDepth(child));
  8. }
  9. return result;
  10. }