LeetCode111—Minimum Depth of Binary Tree

来源:互联网 发布:淘宝店铺审核通过不了 编辑:程序博客网 时间:2024/05/01 07:47

LeetCode111—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.

就是计算从根到叶子节点所要经历节点个数的最小值(树的最小高度)。

分析

就是dfs了,写一个函数判断是否是叶子节点,如果是叶子节点就判断当前高度是否是最低的,如果是就更新最小值,否则递归返回。

代码

class Solution {private:    bool isLeafNode(TreeNode*root)//判断是否为叶子节点    {        if (root->left == NULL&&root->right == NULL)            return true;        else            return false;    }    void dfs(TreeNode *root, int &minCount,int sum)    {        if (root == NULL)        {            return;        }        if (isLeafNode(root))        {            if (sum < minCount)                minCount = sum;        }        else        {            sum++;            dfs(root->left,minCount,sum);            dfs(root->right, minCount, sum);        }    }public:    int minDepth(TreeNode* root) {        if(root == NULL)            return 0;        int minCount = INT_MAX;        int sum = 1;        dfs(root, minCount, sum);        return minCount;    }};
1 0
原创粉丝点击