559. N叉树的最大深度

桃扇骨 2023-02-18 08:03 155阅读 0赞

题目来源

559. N叉树的最大深度

题目解析

层次遍历

  1. class Solution {
  2. public int maxDepth(Node root) {
  3. if (root == null){
  4. return 0;
  5. }
  6. int ans = 0;
  7. LinkedList<Node> list = new LinkedList<>();
  8. list.offer(root);
  9. while (!list.isEmpty()){
  10. int size = list.size();
  11. LinkedList<Node> tmp = new LinkedList<>();
  12. for (int i = 0; i < size; i++){
  13. Node pop = list.pop();
  14. for (Node child : pop.children){
  15. tmp.offer(child);
  16. }
  17. }
  18. list = tmp;
  19. ans++;
  20. }
  21. return ans;
  22. }
  23. }

在这里插入图片描述

递归

首先来看一种常见的递归解法,就是需要有一个当前深度,然后带一个全局变量res进去。在递归函数中,如果node为空,直接返回。若子结点数组为空,那么结果res和cur比较取较大值。否则就遍历子结点数组,对每个子结点调用递归函数,这里的cur要自增1

  1. class Solution {
  2. private int ans = 0;
  3. public int maxDepth(Node root) {
  4. helper(root, 1);
  5. return ans;
  6. }
  7. private void helper(Node root, int depth){
  8. if (root == null){
  9. return;
  10. }
  11. if (root.children.isEmpty()){
  12. ans = Math.max(ans, depth) ;
  13. }
  14. for (Node child: root.children) {
  15. helper(child, depth + 1);
  16. }
  17. }
  18. }

解法2

  1. public int maxDepth(Node root) {
  2. if (root == null){
  3. return 0;
  4. }
  5. int ans = 0;
  6. for (Node child : root.children){
  7. ans = Math.max(ans, maxDepth(child));
  8. }
  9. return ans + 1;
  10. }

直接主函数中递归,首先判空,否则就是遍历子结点数组,然后对每个子结点调用递归函数的返回值加1后跟res相比,取较大值更新结果res

  1. class Solution {
  2. public int maxDepth(Node root) {
  3. if (root == null){
  4. return 0;
  5. }
  6. int ans = 1;
  7. for (Node child : root.children){
  8. ans = Math.max(ans, maxDepth(child) + 1);
  9. }
  10. return ans;
  11. }
  12. }

在这里插入图片描述

发表评论

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

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

相关阅读

    相关 559. N 深度

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