#543. Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
这道题实际是求从一个叶子节点到另一个叶子节点的最长路径。所以要求出每一个节点的深度,最长的深度就是最后的直径。
var diameterOfBinaryTree = function(root) {
let dia = 0;
traverse(root);
return dia;
function traverse(root) {
if(!root) {
return 0;
}
const left = traverse(root.left);
const right = traverse(root.right);
dia = Math.max(dia,left+right);
return 1+Math.max(left,right);
}
};```