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(深度优先遍历):

深度优先遍历,定义一个队列q用来存储已访问过节点的左子树和右子树,定义两个树节点first、last用来标记队列中该层最前面的树节点和最后面的树节点。若first=last,则depth+1。若该节点的左子树和右子树均为空,则找到minimum depth跳出循环,返回depth.否则,继续循环。

代码:

class Solution {
public:
    int run(TreeNode *root) {
        if(!root)
            return 0;
        queue<TreeNode*> q;
        TreeNode *first,*last;
        int depth,size;
        last=first=root;
        depth=1;
        q.push(root);
        while(q.size())
        {
            first=q.front();
            q.pop();            
            size=q.size();
            if(first->left)
                q.push(first->left);
            if(first->right)
                q.push(first->right);
            if(q.size()==size) 
                break;
            if(last==first)
            {
                depth++;
                if(q.size())
                    last=q.back();
            }
        }
        return depth;
        
    }
};

解题思路2(递归)

若为空树返回0;

若左子树为空,则返回右子树的最小深度+1;(加1是因为要加上根这一层,下同)

若右子树为空,则返回左子树的最小深度+1;

若左右子树均不为空,则取左、右子树最小深度的较小值,+1;

代码:

class Solution {
public:
    int run(TreeNode *root) 
    {
        if(root == NULL) return 0;
        if(root->left == NULL) // 若左子树为空,则返回右子树的最小深度+1
        {
            return run(root->right)+1;
        }
        if(root->right == NULL) // 若右子树为空,则返回左子树的最小深度+1
        {
            return run(root->left)+1;
        }
        // 左右子树都不为空时,取较小值
        int leftDepth = run(root->left);
        int rightDepth = run(root->right);
        return (leftDepth<rightDepth)?(leftDepth+1):(rightDepth+1);
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值