var maxDepth = function (root) { if (root == null) { return 0 } else { let left = maxDepth(root.left) let right = maxDepth(root.right) console.log(left) return Math.max(left, right) + 1 }};
# Definition for a binary tree node.class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
复杂度分析
时间复杂度:O(N),其中 N 为节点数。
空间复杂度:O(h),其中 h 为树的深度,最坏的情况 h 等于 N,其中 N 为节点数,此时树退化到链表。