File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * class TreeNode {
4+ * val: number
5+ * left: TreeNode | null
6+ * right: TreeNode | null
7+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+ * this.val = (val===undefined ? 0 : val)
9+ * this.left = (left===undefined ? null : left)
10+ * this.right = (right===undefined ? null : right)
11+ * }
12+ * }
13+ */
14+
15+ /**
16+ *
17+ * Time Complexity: O(n)
18+ * Space Complexity: O(n)
19+ */
20+ function maxDepth ( root : TreeNode | null ) : number {
21+ if ( ! root ) {
22+ // tree is empty
23+ return 0
24+ } else if ( ! root . left && ! root . right ) {
25+ // tree has no children
26+ return 1
27+ } else {
28+ // tree has at least one child
29+ return 1 + Math . max ( maxDepth ( root . left ) , maxDepth ( root . right ) )
30+ }
31+ } ;
You can’t perform that action at this time.
0 commit comments