Maximum Depth of Binary Tree leetcode

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Subscribe to see which companies asked this question

非递归实现:

int maxDepth(TreeNode* root) {
int maxDepth = ;
if (root == nullptr)
return maxDepth;
stack<TreeNode*> sta;
sta.push(root);
TreeNode* lastRoot = root;
while (!sta.empty())
{
root = sta.top();
if (lastRoot != root->right)
{
if (lastRoot != root->left) {
if (root->left != nullptr) {
sta.push(root->left);
continue;
}
}
if (root->right != nullptr) {
sta.push(root->right);
continue;
}
maxDepth = sta.size() > maxDepth ? sta.size() : maxDepth;
}
lastRoot = root;
sta.pop();
}
return maxDepth;
}

递归实现:

int maxDepth(TreeNode* root) {
if (root == nullptr)
return ;
int leftDepth = maxDepth(root->left) + ;
int rightDepth = maxDepth(root->right) + ;
return leftDepth > rightDepth ? leftDepth : rightDepth;
}
上一篇:CentOS 7 Gitlab+Jenkins持续集成+自动化部署


下一篇:ios开发-MapKit(地图框架)使用简介