22 Diameter of Binary Tree

57 阅读1分钟

543. Diameter of Binary Tree

此题就是求树最大深度过程中添加了一步,求left + right最大值的问题

解题思路

  1. 递归求解左右子树最大深度时,left + right 的和如果大于 假设的最大 max diameter,则取 left + right

代码

/**
 * 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 max = 0
    const maxDepth = (node) => {
        if(node == null) return 0
        let left = maxDepth(node.left)
        let right = maxDepth(node.right)
        max = Math.max(max, left + right)
        return Math.max(right, left) + 1
    }
    maxDepth(root)
    return max
};