Minimum Depth of Binary Tree

本文详细介绍了使用C++和Java两种语言实现计算二叉树最小深度的方法,通过递归和广度优先搜索算法找到从根节点到最近叶子节点的最短路径长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

C++版:

#include <iostream>

using namespace std;
struct TreeNode {
   int val;
   TreeNode *left;
   TreeNode *right;
   TreeNode(int x):val(x),left(NULL),right(NULL) {}
};

class Solution {
public:
     int minDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root)
        {
            if(root->left == NULL && root->right == NULL)
                return 1;
            else if(root->left == NULL)
                return minDepth(root->right) + 1;
            else if(root->right == NULL)
                return minDepth(root->left) + 1;
            return min(minDepth(root->left), minDepth(root->right)) + 1;
        }
        return 0;

    }
};

int main(){
    TreeNode *a = new TreeNode(1);
    TreeNode *b = new TreeNode(2);
    TreeNode *c = new TreeNode(3);
    TreeNode *d = new TreeNode(4);
    TreeNode *e = new TreeNode(5);
    TreeNode *f = new TreeNode(6);
    TreeNode *g = new TreeNode(7);

    a->left = b;
    a->right = c;
    b->left = d;
    b->right = e;
    c->left = f;
    c->right = g;
    Solution s1;
    int s = s1.minDepth(a);
    cout<<"the minDepth of the tree is:"<<s<<endl;
    return 0;
}

  Java版:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if( root == null) {
            return 0;
        }
        
        LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
        LinkedList<Integer> counts = new LinkedList<Integer>();
        
        nodes.add(root);
        counts.add(1);
        
        while(!nodes.isEmpty()) {
            TreeNode curr = nodes.remove();
            int count = counts.remove();
            
            if(curr.left != null) {
                nodes.add(curr.left);
                counts.add(count + 1);
            }
            
            if(curr.right != null) {
                nodes.add(curr.right);
                counts.add(count + 1);
            }
            
            if(curr.left == null && curr.right == null) {
                return count;
            }
        }
        return 0;
    }
}

  

转载于:https://www.cnblogs.com/zlz-ling/p/4043240.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值