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

Create 543-Diameter-of-Binary-Tree#113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
neetcode-gh merged 2 commits intoneetcode-gh:mainfromArwaNayef:patch-9
Apr 9, 2022
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletionsjava/543-Diameter-of-Binary-Tree.java
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
class Solution {
private static int treeDiameter = 0;

public int diameterOfBinaryTree(TreeNode root) {
calculateHeight(root);
return treeDiameter-1;
}

private static int calculateHeight(TreeNode currentNode) {
if (currentNode == null)
return 0;

int leftTreeHeight = calculateHeight(currentNode.left);
int rightTreeHeight = calculateHeight(currentNode.right);

// if the current node doesn't have a left or right subtree, we can't have
// a path passing through it, since we need a leaf node on each side
if (leftTreeHeight != 0 && rightTreeHeight != 0) {

// diameter at the current node will be equal to the height of left subtree +
// the height of right sub-trees + '1' for the current node
int diameter = leftTreeHeight + rightTreeHeight + 1;

// update the global tree diameter
treeDiameter = Math.max(treeDiameter, diameter);
}

// height of the current node will be equal to the maximum of the heights of
// left or right subtrees plus '1' for the current node
return Math.max(leftTreeHeight, rightTreeHeight) + 1;
}
}

[8]ページ先頭

©2009-2025 Movatter.jp