File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +32
-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+ * - 시간 복잡도: O(n)
18+ * - 공간 복잡도: O(n)
19+ * @param root
20+ */
21+ function maxDepth ( root : TreeNode | null ) : number {
22+ if ( ! root ) return 0 ;
23+ let max = 0 ;
24+ let stack : [ TreeNode | null , number ] [ ] = [ [ root , 1 ] ] ;
25+ while ( stack . length > 0 ) {
26+ const [ node , depth ] = stack . pop ( ) ;
27+ max = Math . max ( depth , max ) ;
28+ if ( node . left ) stack . push ( [ node . left , depth + 1 ] ) ;
29+ if ( node . right ) stack . push ( [ node . right , depth + 1 ] ) ;
30+ }
31+ return max
32+ }
You can’t perform that action at this time.
0 commit comments