Minimum Depth of Binary Tree--LeetCode

来源:互联网 发布:sql触发器类型 编辑:程序博客网 时间:2024/05/17 23:13

1.题目

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.

2.题意

给定一个二叉树,,找到它的最小深度。
最小深度是沿着最短路径从根节点到最近的叶节点的节点数。

3.分析

本题类似于Maximum Depth of Binary Tree
不同之处在于判断最小深度需要对叶子节点进行判断
不能取它左右子树的较小深度作为最小深度
因为如果一个节点只有左子树或只有右子树,其值为0
而在求最大深度的时候,一定会取较大值,所以不需要这个判断
注意不要遗漏对叶子节点的判断,将if(root->left == nullptr)写成if(root->left)或是将min写成max

4.代码

1)递归

class Solution {public:    int minDepth(TreeNode* root) {        if(root == nullptr)            return 0;        if(root->left == nullptr)            return minDepth(root->right) + 1;        if(root->right == nullptr)            return minDepth(root->left) + 1;        return min(minDepth(root->left), minDepth(root->right)) + 1;    }};

2)非递归

class Solution {public:    int minDepth(TreeNode* root) {        if(root == nullptr)            return 0;        queue<TreeNode*> q;        q.push(root);        int level = 0;        while(!q.empty())        {            ++level;            int len = q.size();            for(int i = 0; i < len; ++i)            {                TreeNode *node = q.front();                q.pop();                if(node->left == nullptr && node->right == nullptr)                    return level;                if(node->left)                    q.push(node->left);                if(node->right)                    q.push(node->right);            }        }        return level;    }};
原创粉丝点击