前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-面试题55-1-二叉树的深度

LeetCode-面试题55-1-二叉树的深度

作者头像
benym
发布2022-07-14 15:32:37
1490
发布2022-07-14 15:32:37
举报
文章被收录于专栏:后端知识体系后端知识体系

# LeetCode-面试题55-1-二叉树的深度

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

示例1:

给定二叉树 [3,9,20,null,null,15,7]

代码语言:javascript
复制
    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

  • 提示:
    1. 节点总数 <= 10000

# 解题思路

方法1、DFS:

既然要求树的深度自然少不了深度优先遍历,通过比较左子树的深度和右子树的深度判断最大深度,之后加上根节点

方法2、BFS:

层序遍历一般也就是广度优先遍历,在原本队列的实现基础上,对一个层进行循环约束即可,每遍历完一层,深度就+1

# Java代码

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)
            return 0;
        int nleft = maxDepth(root.left);
        int nright = maxDepth(root.right);
        return Math.max(nleft,nright)+1;
    }
}

# Python代码

代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root: return 0
        queue , depth = [] , 0
        queue.append(root)
        while queue:
            for i in range(len(queue)):
                temp = queue.pop(0)
                if temp.left:
                    queue.append(temp.left)
                if temp.right:
                    queue.append(temp.right)
            depth+=1
        return depth
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-05-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • # LeetCode-面试题55-1-二叉树的深度
    • # 解题思路
      • # Java代码
        • # Python代码
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档