算法 二叉树的直径
题目
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
示例 :
给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
代码
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var diameterOfBinaryTree = function(root) {
let result = 0
function getDepth(root) {
// 叶子节点记为0
if(!root) return 0
// 以该节点为根节点,左右子树的深度
const leftDepth = getDepth(root.left)
const rightDepth = getDepth(root.right)
result = Math.max(result,(leftDepth + rightDepth ))
// 该节点的高度
return Math.max(leftDepth,rightDepth) + 1
}
getDepth(root)
return result
};
总结
function getDepth(root) {
// 叶子节点记为0
if(!root) return 0
// 以该节点为根节点,左右子树的深度
const leftDepth = getDepth(root.left)
const rightDepth = getDepth(root.right)
// 该节点的高度
return Math.max(leftDepth,rightDepth) + 1
}
该段代码稍加修改可适用大多数二叉数深度的问题