File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time complexity: O(n)
2+ // Space complexity: O(n)
3+
4+ /**
5+ * Definition for a binary tree node.
6+ * function TreeNode(val, left, right) {
7+ * this.val = (val===undefined ? 0 : val)
8+ * this.left = (left===undefined ? null : left)
9+ * this.right = (right===undefined ? null : right)
10+ * }
11+ */
12+ /**
13+ * @param {TreeNode } root
14+ * @return {number }
15+ */
16+ var maxDepth = function ( root ) {
17+ let answer = 0 ;
18+
19+ const dfs = ( current , depth ) => {
20+ if ( ! current ) {
21+ return ;
22+ }
23+
24+ if ( answer < depth ) {
25+ answer = depth ;
26+ }
27+
28+ if ( current . left ) {
29+ dfs ( current . left , depth + 1 ) ;
30+ }
31+
32+ if ( current . right ) {
33+ dfs ( current . right , depth + 1 ) ;
34+ }
35+ } ;
36+
37+ dfs ( root , 1 ) ;
38+ return answer ;
39+ } ;
You can’t perform that action at this time.
0 commit comments