来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
DFS 递归法
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number} */ var diameterOfBinaryTree = function(root) { let res = 0; function depth(node) { if (!node) { return 0; } let left = depth(node.left); let right = depth(node.right); res = Math.max(res, left + right); return Math.max(left, right) + 1; } depth(root); return res; };
原文:https://www.cnblogs.com/liu-xin1995/p/12458906.html