Check for Balanced Tree | Diameter of Binary Tree

I came across these 2 questions and found similarities in both of them.

Now, let's discuss the solution:

  1. Check for a balanced tree:

Here First we need to find the height of the binary tree for both part i.e. left tree and right tree for each node, if the difference between them is greater than 1 then it is not balanced tree, return false.

How to find the height of the binary tree? here is the code for the same.

To the above code send the root and it will give the maximum height of that node.

Here is the code for the same:

Here we are calling the height function to all nodes of the tree, and checking for the validations of it.

2. Diameter of binary tree

Here we need to find the maximum path between 2 nodes.

So here comes the solution similar to same, only few modification are there.

The logic is the same for both, but here we are to check for Math.max for the same, and previously we are checking for the validations for the same.

So the difference is only 2 lines of code, the rest of the part is the same, and logic wise both are the same.

Thank you for reading!

Happy Coding!

Software Developer

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