File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +35
-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+ function maxDepth ( root : TreeNode | null ) : number {
16+ // DFS (혹은 BFS) 후 깊이 체크하기
17+ if ( ! root ) return 0 ;
18+
19+ const stack : [ TreeNode , number ] [ ] = [ [ root , 1 ] ] ;
20+ let maxDepth = 0 ;
21+
22+ while ( stack . length > 0 ) {
23+ const [ node , depth ] = stack . pop ( ) ! ;
24+ maxDepth = Math . max ( maxDepth , depth ) ;
25+
26+ if ( node . right ) {
27+ stack . push ( [ node . right , depth + 1 ] ) ;
28+ }
29+ if ( node . left ) {
30+ stack . push ( [ node . left , depth + 1 ] ) ;
31+ }
32+ }
33+
34+ return maxDepth ;
35+ } ;
You can’t perform that action at this time.
0 commit comments