LeetCode: Diameter of Binary Tree Solution

Sum of max height of 2 subtrees

Approach

Basically calculate the height of the tree

During the calculation, intercept a step which takes the sum of two subtrees' height

Get the max

Implementation

1var diameterOfBinaryTree = function (root) {
2 let max = -Infinity
3
4 const recursion = node => {
5 if (!node) return 0
6
7 let maxHeightLeft = recursion(node.left)
8 let maxHeightRight = recursion(node.right)
9
10 max = Math.max(max, maxHeightLeft + maxHeightRight)
11
12 return Math.max(maxHeightLeft, maxHeightRight) + 1
13 }
14
15 recursion(root)
16
17 return max
18}

References

Original problem

Similar problems

Diameter of N-Ary Tree

Longest Path With Different Adjacent Characters

Comments

Loading comments...

Tags

leetcode

tree

binary tree

recursion

dfs

Next Post

LeetCode: Kth Smallest Element in a BST

Inorder traversal

Previous Post

HoningJS

Search Posts