543. Diameter of Binary Tree

202408301009
tags: #tree

var diameterOfBinaryTree = function(root) {
	let res = 0;
	
	const dfs = (node) => {
		if (node == null) {
			return 0;
		}
		const leftMax = dfs(node.left);
		const rightMax = dfs(node.right);
		res = Math.max(res, leftMax + rightMax);
		return Math.max(leftMax, rightMax) + 1;
	}
	
	dfs(root);
	return res;
};

Reference

https://leetcode.com/problems/diameter-of-binary-tree