543. Diameter of Binary Tree

2021-02-10  本文已影响0人  jluemmmm

求二叉树的直径,深度优先遍历。

/**
 * 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}
 */
let max = 0
var diameterOfBinaryTree = function(root) {
    dfs(root)
    return max
};

var dfs = function(root) {
    if(root === null) return 0
    let left = root.left !== null ? dfs(root.left) : 0
    let right = root.right !== null ? dfs(root.right) : 0
    let cur = left + right
    if (max < cur) max = cur
    return Math.max(left, right) + 1
}
上一篇 下一篇

猜你喜欢

热点阅读