LeetCode_559.N叉树的最大深度

小灰灰 2023-02-25 10:09 102阅读 0赞

在这里插入图片描述
题解_C:

  1. /**
  2. * Definition for a Node.
  3. * struct Node {
  4. * int val;
  5. * int numChildren;
  6. * struct Node** children;
  7. * };
  8. */
  9. int* maxDepth(struct Node* root) {
  10. if(!root){
  11. return 0;
  12. }
  13. int max = 0;
  14. int i;
  15. for(i=0; i<root->numChildren; ++i){
  16. int t = maxDepth(root->children[i]);
  17. max = max>t?max:t;
  18. }
  19. return max+1;
  20. }

题解_Java:

  1. /*
  2. // Definition for a Node.对树节点的定义
  3. class Node {
  4. public int val;
  5. public List<Node> children; //没懂
  6. public Node() {}
  7. public Node(int _val) {
  8. val = _val;
  9. }
  10. public Node(int _val, List<Node> _children) {
  11. val = _val;
  12. children = _children;
  13. }
  14. };
  15. */
  16. class Solution {
  17. public int maxDepth(Node root) {
  18. if (root == null) {
  19. return 0;
  20. } else if (root.children.isEmpty()) {
  21. return 1;
  22. } else {
  23. List<Integer> heights = new LinkedList<>();
  24. for (Node item : root.children) {
  25. //增强for循环
  26. heights.add(maxDepth(item));
  27. }
  28. return Collections.max(heights) + 1;
  29. }
  30. }
  31. }

相关知识:
增强for语句

  • 语法
    for(元素类型 e:数组或集合对象){
    }
    冒号左边是定义变量,右边必须是数组或集合类型

    int[] arr = {

    1. 1,2,3};

    for(int i:arr){

    System.out.println(i);
    }
    /增强for内部会依次把arr中的元素赋给变量i/

  • 增强for的优缺点
    只能从头到尾的遍历数组或集合,而不能只遍历部分;
    在遍历list或数组时,不能获取当前元素下标;
    增强for使用简单,简洁,代码优雅,这是它唯一的优点;
    增强for比使用呢迭代器方便一点

PS:如果能使用增强for循环,一定要优先使用

发表评论

表情:
评论列表 (有 0 条评论,102人围观)

还没有评论,来说两句吧...

相关阅读

    相关 559. N 深度

    给定一个 N 叉树,找到其最大深度。 最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。 N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。