来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7],

    1. 3

    / \ 9 20 / \ 15 7 返回它的最大深度 3 。

    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 maxDepth = function(root) {
    14. if (!root) return 0;
    15. let stack = [root],
    16. depth = 0;
    17. while (stack.length) {
    18. ++depth;
    19. let temp = [];
    20. for (let item of stack) {
    21. if (item) {
    22. item.left && temp.push(item.left);
    23. item.right && temp.push(item.right);
    24. }
    25. }
    26. stack = temp;
    27. }
    28. return depth;
    29. };