一般二叉树dfs的解法就是先想象return dfs(left) +-*/ dfs(right) +C。根据题目要求去填充中间的操作数和常数赋予每一层返回值的实际意义。

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {number}
    12. */
    13. var diameterOfBinaryTree = function (root) {
    14. let count = 0
    15. const dfs = (node) => {
    16. if (!node) {
    17. return 0
    18. }
    19. let right = 0,
    20. left = 0
    21. if (node.right) {
    22. right = dfs(node.right) + 1
    23. }
    24. if (node.left) {
    25. left = dfs(node.left) + 1
    26. }
    27. count = Math.max(right + left, count)
    28. return Math.max(right, left)
    29. }
    30. dfs(root)
    31. return count
    32. };