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+ * 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+ let max = 0 ;
15+
16+ const dfs = ( node , depth ) => {
17+ if ( node ) {
18+ dfs ( node . left , depth + 1 ) ;
19+ dfs ( node . right , depth + 1 ) ;
20+ } else { // when this node is null
21+ max = Math . max ( max , depth ) ;
22+ }
23+ }
24+
25+ dfs ( root , 0 ) ;
26+
27+ return max ;
28+ } ;
29+
30+ // ์๊ฐ๋ณต์ก๋ O(n) -> ํธ๋ฆฌ์ ๋ชจ๋ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๋ฉด์ ์ด ๋
ธ๋์ ๊ฐฏ์์ธ n๊ฐ ๋งํผ์ ์๊ฐ๋ณต์ก๋๋ฅผ ๊ฐ์ง๊ฒ ๋๋ฏ๋ก
31+ // ๊ณต๊ฐ๋ณต์ก๋ O(h) -> ์ฝ์คํ์ ์ต๋ ๊ธธ์ด๋ ํธ๋ฆฌ์ ๊น์ด์ ๋์ผํ๋ฏ๋ก
32+
You canโt perform that action at this time.
0 commit comments