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.   注意与求树的高度的区别。

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>
#include<new>
#include<vector>
using namespace std;

//Definition for binary tree
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution
{
public:
    int minDepth(TreeNode *root)
    {
        if(root)
        {
            if(root->left==NULL&&root->right==NULL)
                return 1;
            int lmin=minDepth(root->left);
            int rmin=minDepth(root->right);
            if(root->left&&root->right==NULL)
                return lmin+1;
            if(root->left==NULL&&root->right)
                return rmin+1;
            return (lmin<= rmin)?(lmin+1):(rmin+1);
        }
        return 0;
    }
    void createTree(TreeNode *&root)
    {
        int i;
        cin>>i;
        if(i!=0)
        {
            root=new TreeNode(i);
            if(root==NULL)
                return;
            createTree(root->left);
            createTree(root->right);
        }
    }
};
int main()
{
    Solution s;
    TreeNode *root;
    s.createTree(root);
    cout<<s.minDepth(root)<<endl;
}

 

相关文章
|
6月前
Leetcode Minimum Depth of Binary Tree (面试题推荐)
计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。 我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。
24 0
LeetCode 111. Minimum Depth of Binary Tree
给定一棵二叉树,返回其最短深度. 题目要求是返回一颗二叉树从根节点到到所有叶节点中,深度最小的值.
60 0
LeetCode 111. Minimum Depth of Binary Tree
LeetCode 104. Maximum Depth of Binary Tree
给定一颗二叉树,返回其最大深度. 注意:深度从1开始计数.
45 0
LeetCode 104. Maximum Depth of Binary Tree
LeetCode之Maximum Depth of Binary Tree
LeetCode之Maximum Depth of Binary Tree
85 0
|
Java
[LeetCode] Minimum Depth of Binary Tree
链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/难度:Easy题目:111.
824 0
|
Java
[LeetCode] Maximum Depth of Binary Tree
链接:https://leetcode.com/submissions/detail/136407355/难度:Easy题目:104. Maximum Depth of Binary Tree Given a binary tree, find its maximum depth.
950 0