您的位置:首页 > 编程语言 > C语言/C++

LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)

2017-08-03 22:31 561 查看
二叉树最小深度:

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to
the nearest leaf node.

二叉树根节点到最近叶子节点的距离



递归解法:递归计算当前节点的左子树和右子树的最小深度,返回更小的深度加1(特殊情况:单一子树为空时,对应最小深度为0,但是并非叶子节点,此时返回非空子树的深度。递归至E节点:左子树为空,最小深度为0;右子树非空,最小深度为1;返回右子树最小深度);结束递归的条件:左右子树都为空。

class TreeNode{
public:
TreeNode(){}
TreeNode(int _val){val=_val;}
TreeNode* left;TreeNode* right;
int val;
};
class Solution {
public:
int run(TreeNode *root) {
if(root==nullptr){return 0;}
int m=run(root->left);
int n=run(root->right);
if(m==0||n==0)//单一子树为空时,返回非空的节点深度加1
{return m+n+1;}
else
{ return m>n?n+1:m+1;}
}
};
遍历非递归解法:初始化,根节点入队列,当前层节点个数,最小深度depth。只要队列不为空,取队首节点,出队,当前层size减1,当前节点左右非空子树入队;若左右子树都为空,返回最小深度depth。如果当前层size为0,说明上一层节点遍历完了,更新size,最小深度depth加1。

#include<queue>
class Solution {
public:
int run(TreeNode *root) {
int depth=1;//最小深度
int treeSize=0;//当前层节点个数
if(root==nullptr) return 0;
queue<TreeNode*>row;
row.push(root);
treeSize=row.size();
TreeNode * temp;
while(!row.empty())
{
temp=row.front();
row.pop();
treeSize--;
if(temp->left==nullptr&&temp->right==nullptr)
return depth;
if(temp->left!=nullptr)
row.push(temp->left);
if(temp->right!=nullptr)
row.push(temp->right);
if (treeSize==0)//当前层节点遍历结束
{
treeSize=row.size();//下一层的节点个数
depth++;//最小深度加1
}
}
return depth;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐