Skip to content

Commit 880e436

Browse files
[CPP] 104. Maximum Depth of Binary Tree
1 parent cd9f44d commit 880e436

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
13+
// Using Stack
14+
// class Solution {
15+
// public:
16+
// int maxDepth(TreeNode* root) {
17+
// if (root == NULL) return 0;
18+
// stack<pair<TreeNode*, int>> stk;
19+
// int res = 0;
20+
// stk.push({root, 1});
21+
22+
// while (!stk.empty()) {
23+
// auto t = stk.top();
24+
// res = max(res, t.second);
25+
// stk.pop();
26+
// if (t.first->left) stk.push({t.first->left, t.second+1});
27+
// if (t.first->right) stk.push({t.first->right, t.second+1});
28+
// }
29+
// return res;
30+
// }
31+
// };
32+
33+
// Using Recursion
34+
class Solution {
35+
public:
36+
int maxDepth(TreeNode* root) {
37+
if (root == NULL) return 0;
38+
return max(maxDepth(root->left)+1, maxDepth(root->right)+1);
39+
}
40+
};

0 commit comments

Comments
 (0)