Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ozkansari/f9cde128fbe28c8a4987df53c037fce4 to your computer and use it in GitHub Desktop.
Save ozkansari/f9cde128fbe28c8a4987df53c037fce4 to your computer and use it in GitHub Desktop.
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3293/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
class BinaryTreeDiameterCalculatorWithRecursion {
public int diameterOfBinaryTree(TreeNode root) {
SolutionFinder finder = new SolutionFinder();
findDepth(root, finder);
return finder.value;
}
/**
*
*/
private int findDepth(TreeNode currentRoot, SolutionFinder finder){
if(currentRoot==null) {
return 0;
}
// Calculate the depth of a node in the usual way
// max(depth of node.left, depth of node.right) + 1
int leftDepth = findDepth(currentRoot.left, finder);
int rightDepth = findDepth(currentRoot.right, finder);
int currentDepth = 1 + Math.max(leftDepth,rightDepth);
// Check if current diameter is the maximum and save it
int currentDiameter = leftDepth + rightDepth;
finder.suggestDiameter(currentDiameter);
return currentDepth;
}
private class SolutionFinder {
private int value = 0;
private void suggestDiameter(int currentDiameter){
if(this.value < currentDiameter) {
this.value = currentDiameter;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment