LeetCode: Diameter of Binary Tree Solution
Sum of max height of 2 subtreesApproach
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 = -Infinity34 const recursion = node => {5 if (!node) return 067 let maxHeightLeft = recursion(node.left)8 let maxHeightRight = recursion(node.right)910 max = Math.max(max, maxHeightLeft + maxHeightRight)1112 return Math.max(maxHeightLeft, maxHeightRight) + 113 }1415 recursion(root)1617 return max18}
References
Similar problems
Diameter of N-Ary Tree
Longest Path With Different Adjacent Characters
Comments
Loading comments...
Tags
leetcode
tree
binary tree
recursion
dfs
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Kth Smallest Element in a BST
Inorder traversal
Previous Post
LeetCode: Maximum Depth of Binary Tree
Explanation is hard