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

二叉树最小深度:

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;
    }
};







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值