二叉树---二叉树的最大深度

题目:

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

思路一:递归法。使用前序遍历或后序遍历,前序遍历求得树的最大深度,后序遍历求得节点的高度(根节点的高度就是树的最大深度)。本题解法使用前序遍历。

代码:

public int maxDepth(TreeNode root) {
        return getDepth(root);
    }
public int getDepth(TreeNode node){
        if(node==null)
            return 0;
        int leftDepth=getDepth(node.left);
        int rightDepth=getDepth(node.right);
        int depth=1+Math.max(leftDepth,rightDepth);
        return depth;
    }

思路二:迭代法。使用层序遍历。每遍历一层,depth+1 。

代码:

public int maxDepth(TreeNode root) {
        if(root==null)
            return 0;
        Queue<TreeNode> queue=new LinkedList<>();
        int depth=0;
        queue.offer(root);
        while(!queue.isEmpty()){
            int len=queue.size();
            depth++;
            while(len>0){
                TreeNode node=queue.peek();
                if(node.left!=null) queue.offer(node.left);
                if(node.right!=null) queue.offer(node.right);
                queue.poll();
                len--;
            }
        }
        return depth;
    }

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-17 15:18:06       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-17 15:18:06       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-17 15:18:06       62 阅读
  4. Python语言-面向对象

    2024-07-17 15:18:06       72 阅读

热门阅读

  1. AI技术在企业招聘中的应用案例分析

    2024-07-17 15:18:06       26 阅读
  2. 土土土土土土土土圭

    2024-07-17 15:18:06       22 阅读
  3. ElasticSearch学习之路

    2024-07-17 15:18:06       24 阅读
  4. android include 和 merge 区别

    2024-07-17 15:18:06       21 阅读
  5. python基础篇(12):继承

    2024-07-17 15:18:06       23 阅读
  6. Spring解决循环依赖问题的四种方法

    2024-07-17 15:18:06       19 阅读
  7. 人工智能与人类社会的共生共荣

    2024-07-17 15:18:06       19 阅读
  8. Catboost 不能做多变量回归?

    2024-07-17 15:18:06       20 阅读
  9. Qt将毫秒转化为时分秒格式

    2024-07-17 15:18:06       23 阅读