https://leetcode.com/problems/maximum-depth-of-binary-tree/description/?envType=study-plan-v2&envId=top-interview-150
/**
* 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) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL){ return 0; }
vector<pair<int, TreeNode*>> stack;
stack.push_back(pair<int, TreeNode*>(1, root));
int max_depth = 0;
while(!stack.empty()){
pair<int, TreeNode*> curr = stack.back();
int curr_depth = curr.first;
TreeNode* curr_node = curr.second;
max_depth = max(max_depth, curr_depth);
stack.pop_back();T
if (curr_node->left != NULL){
stack.push_back(pair<int, TreeNode*>(curr_depth+1, curr_node->left));
}
if (curr_node->right != NULL){
stack.push_back(pair<int, TreeNode*>(curr_depth+1, curr_node->right));
}
}
return max_depth;
}
};
Time Complexity
stack vector holds nodes waiting to be processed. The maximum number of nodes in it at any time depends on tree shape: