int minDepth(TreeNode *root) {
vector<TreeNode*> nodes;
vector<int> depths;
int min_depth = 0;
if(root != NULL)
{
nodes.push_back(root);
depths.push_back(1);
}
while(!nodes.empty())
{
TreeNode* cur_node = nodes.back();
int cur_node_depth = depths.back();
TreeNode* left_child = cur_node->left;
TreeNode* right_child = cur_node->right;
nodes.pop_back();
depths.pop_back();
if(right_child != NULL)
{
nodes.push_back(right_child);
int right_child_depth = cur_node_depth + 1;
depths.push_back(right_child_depth);
}
if(left_child != NULL)
{
nodes.push_back(left_child);
int left_child_depth = cur_node_depth + 1;
depths.push_back(left_child_depth);
}
if(left_child == NULL && right_child == NULL)
{
if(min_depth == 0)
{
min_depth = cur_node_depth;
}
else if(cur_node_depth < min_depth)
{
min_depth = cur_node_depth;
}
}
}
return min_depth;
}
参考Binary Tree Postorder Traversal遍历方法
[LeetCode] Minimum Depth of Binary Tree
最新推荐文章于 2021-03-26 11:04:55 发布