543. Diameter of Binary Tree — LeetCode(Python)

Problem:

Given the root of a binary tree, return the length of the diameter of the tree.

Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
Input: root = [1,2]
Output: 1
  • The number of nodes in the tree is in the range [1, 104].
  • -100 <= Node.val <= 100

Solution:

Explanation —

We can use a depth-first search (DFS) traversal algorithm to solve this problem.

Time Complexity —

Since we are visiting each node only a constant number of times, we can say that our algorithm requires a linear amount of time to run.

I don’t have friends:

Let’s be friends!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store