forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[CPP] 104. Maximum Depth of Binary Tree
- Loading branch information
1 parent
cd9f44d
commit 880e436
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
* Definition for a binary tree node. | ||
* struct TreeNode { | ||
* int val; | ||
* TreeNode *left; | ||
* TreeNode *right; | ||
* TreeNode() : val(0), left(nullptr), right(nullptr) {} | ||
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} | ||
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} | ||
* }; | ||
*/ | ||
|
||
// Using Stack | ||
// class Solution { | ||
// public: | ||
// int maxDepth(TreeNode* root) { | ||
// if (root == NULL) return 0; | ||
// stack<pair<TreeNode*, int>> stk; | ||
// int res = 0; | ||
// stk.push({root, 1}); | ||
|
||
// while (!stk.empty()) { | ||
// auto t = stk.top(); | ||
// res = max(res, t.second); | ||
// stk.pop(); | ||
// if (t.first->left) stk.push({t.first->left, t.second+1}); | ||
// if (t.first->right) stk.push({t.first->right, t.second+1}); | ||
// } | ||
// return res; | ||
// } | ||
// }; | ||
|
||
// Using Recursion | ||
class Solution { | ||
public: | ||
int maxDepth(TreeNode* root) { | ||
if (root == NULL) return 0; | ||
return max(maxDepth(root->left)+1, maxDepth(root->right)+1); | ||
} | ||
}; |