Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

104. 二叉树的最大深度 #19

Open
Labels
@Geekhyt

Description

@Geekhyt

原题链接

DFS 深度优先搜索

树的深度 = 左右子树的最大深度 + 1

constmaxDepth=function(root){if(!root){// 递归终止条件return0}else{constleft=maxDepth(root.left)constright=maxDepth(root.right)returnMath.max(left,right)+1}};
  • 时间复杂度: O(n)
  • 最坏空间复杂度: O(height), height 表示二叉树的高度

BFS 广度优先搜索

层序遍历时记录树的深度。

二叉树的层序遍历可参考轻松拿下二叉树的层序遍历

constmaxDepth=function(root){letdepth=0if(root===null){returndepth}constqueue=[root]while(queue.length){letlen=queue.lengthwhile(len--){constcur=queue.shift()cur.left&&queue.push(cur.left)cur.right&&queue.push(cur.right)}depth++}returndepth};
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp