bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 543. Diameter of Binary Tree

543. Diameter of Binary Tree

Leetcode Solutions

Depth-first Search to Find the Diameter of a Binary Tree

  1. Initialize a global variable diameter to 0 to keep track of the maximum diameter.
  2. Define a recursive function longestPath that computes the height of the subtree rooted at the given node and updates the diameter.
  3. If the current node is None, return 0.
  4. Recursively find the longest path in the left subtree and the right subtree.
  5. Update the diameter with the sum of the longest paths from the left and right if it's greater than the current diameter.
  6. Return the height of the current subtree, which is 1 plus the maximum of the longest paths from the left and right subtrees.
  7. Call longestPath with the root of the tree.
  8. After the recursion completes, return the value of diameter.
UML Thumbnail

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...