Solution Review: Problem Challenge 1

Tree Diameter (medium) #

Given a binary tree, find the length of its diameter. The diameter of a tree is the number of nodes on the longest path between any two leaf nodes. The diameter of a tree may or may not pass through the root.

Note: You can always assume that there are at least two leaf nodes in the given tree.

Created with Fabric.js 1.6.0-rc.1 Example 1: 1 2 3 4 5 6 Output: 5Explaination: The diameter of the tree is: [4, 2, 1, 3, 6]
Created with Fabric.js 1.6.0-rc.1 Example 2: 1 2 3 5 6 7 8 10 9 11 Output: 7Explaination: The diameter of the tree is: [10, 8, 5, 3, 6, 9, 11]

Solution #

This problem follows the Binary Tree Path Sum pattern. We can follow the same DFS approach. There will be a few differences:

  1. At every step, we need to find the height of both children of the current node. For this, we will make two recursive calls similar to DFS.
  2. The height of the current node will be equal to the maximum of the heights of its left or right children, plus ‘1’ for the current node.
  3. The tree diameter at the current node will be equal to the height of the left child plus the height of the right child plus ‘1’ for the current node: diameter = leftTreeHeight + rightTreeHeight + 1. To find the overall tree diameter, we will use a class level variable. This variable will store the maximum diameter of all the nodes visited so far, hence, eventually, it will have the final tree diameter.

Code #

Here is what our algorithm will look like:

Output

0.492s

Tree Diameter: 5 Tree Diameter: 7

Time complexity #

The time complexity of the above algorithm is O(N)O(N), where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space complexity #

The space complexity of the above algorithm will be O(N)O(N) in the worst case. This space will be used to store the recursion stack. The worst case will happen when the given tree is a linked list (i.e., every node has only one child).

Mark as Completed
←    Back
Problem Challenge 1
Next    →
Problem Challenge 2