当前位置:网站首页>Leetcode-104. Maximum Depth of Binary Tree

Leetcode-104. Maximum Depth of Binary Tree

2022-06-11 06:56:00 Eistert

题目

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:
在这里插入图片描述

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -100 <= Node.val <= 100

解法

方法一:深度优先搜索

代码

    /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
    class Solution {
    
        public int maxDepth(TreeNode root) {
    
            if(root == null){
    
                return 0;
            }

            return 1 + Math.max(maxDepth(root.left),maxDepth(root.right));

        }
    }

复杂度分析

  • 时间复杂度:O(n);
  • 空间复杂度:O(height);

方法二:广度优先搜索

我们也可以用【广度优先搜索】的方法来解决这道题目,但我们需要对其进行一些修改,此时我们广度优先搜索队列里存放的是【当前层的所有节点】。每次拓展下一层的时候,不同于广度优先搜索的每次只从队列里拿出一个节点,我们需要将队列里的所有节点都拿出来进行拓展,这样能保证每次拓展完的时候队列里存放的是当前层的所有节点,即我们是一层一层地进行拓展,最后我们用一个变量ans来维护拓展的次数,该二叉树的最大深度即为ans。

代码

        public int maxDepth(TreeNode root) {
    
            if (root == null) {
    
                return 0;
            }

            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            // 将根节点加入队列中
            queue.offer(root);

            // 初识化结果为0
            int ans = 0;
            while (!queue.isEmpty()) {
    
                // 当前层的节点数量
                int size = queue.size();
                while (size > 0) {
    
                    TreeNode node = queue.poll();
                    if (node.left != null) {
    
                        queue.offer(node.left);
                    }

                    if (node.right != null) {
    
                        queue.offer(node.right);
                    }
                    size--;
                }
                // 层数加1
                ans++;
            }
            return ans;
        }

复杂度分析

  • 时间复杂度:O(n);
  • 空间复杂度:O(height);

转载

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/solution/er-cha-shu-de-zui-da-shen-du-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原网站

版权声明
本文为[Eistert]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_39595769/article/details/125126010