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

543. 二叉树的直径 #78

Open
Open
Labels
@Geekhyt

Description

@Geekhyt

原题链接

递归 dfs

  • 一棵二叉树的直径长度是任意两个结点路径长度中的最大值
  • 这条路径可能穿过也可能不穿过根结点

两个公式:

  1. 最长路径 = 左子树最长路径 + 右子树最长路径 + 1 (根结点)
  2. 高度(最大深度) = 左右子树中的最大深度 + 1 (根结点)
constdiameterOfBinaryTree=function(root){letans=1functiondepth(node){if(node===null)return0letL=depth(node.left)letR=depth(node.right)ans=Math.max(ans,L+R+1)returnMath.max(L,R)+1}depth(root)returnans-1}
  • 时间复杂度: O(n)
  • 空间复杂度: O(H),H 为二叉树的高度

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