Skip to content

Commit

Permalink
[CPP] 104. Maximum Depth of Binary Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
UnresolvedCold committed Apr 3, 2022
1 parent cd9f44d commit 880e436
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions cpp/104-Maximum-Depth-of-Binary-Tree.cpp
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);
}
};

0 comments on commit 880e436

Please sign in to comment.