leetcode Minimum Depth of Binary Tree C++题解

题目描述

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.

给出一个二叉树,求其最短路径

最短路径定义:从根节点到最近的叶子节点的路径上的节点个数

思路描述

这道题对于我来说引发的思考比较多

首先明确一个比较大但很重要的概念,二叉树是一个递归的数据结构,因此是一个用来考察递归思维能力的绝佳数据结构。

递归一定是深度优先搜索

首先回忆一下求二叉树高度的代码

int treeHeight(TreeNode *root)
{
    if (root==NULL)
        return 0;
    int left=treeHeight(root->left);
    int right=treeHeight(root->right);
    return 1+max(left,right);
}

类比这个代码于是我只改动了上述代码的一行进行了提交

return 1+min(left,right);

于是就WA了,因为这样做的结果就是不考虑是否为叶子节点都计算了它的深度,这道题要求我们只有在叶子节点才能判断深度,至于如何判断是否是叶子节点,递归到节点为空时,判断其是否有兄弟节点,如果没有,即该空节点的父节点为叶子节点,令该节点的深度为0,其父节点的深度自然为1,如果有兄弟节点,即该空节点的父节点不是叶子节点,令该节点的深度为正无穷(INT_MAX)。就避免了将非叶子节点的深度进行比较。具体代码实现如下

class Solution {
public:
    int minDepth(TreeNode *root)
    {
        return minDepth(root,false);
    }
private:
    int minDepth(TreeNode *root,bool hasBrother)
    {
        if(root==NULL)
        {
            return hasBrother?INT_MAX:0;

        }
        return 1+min(minDepth(root->left,root->right!=NULL),minDepth(root->right,root->left!=NULL));

    }
};

再谈一些对树的递归的认识,树的递归就是代码顺序执行到一个可以递归的地方然后一直递归到最深处,然后逐级向上层返回值完毕之后继续顺序执行。

接下来是非递归的解法,遍历该树,统计每个叶子节点的深度,更新最小值,注意在遍历过程中根据当前深度判断是否需要继续遍历,从而进行剪枝。代码实现如下:

class Solution {
public:
    int minDepth(TreeNode *root)
    {
        if (root==NULL)
            return 0;
        int result=INT_MAX;
        stack<pair<TreeNode *,int> > s;  //申请一个存储节点深度对的栈
        s.push(make_pair(root,1));//压入根节点
        while(!s.empty()) //类似层序遍历树,但不遵循严格的从左到右,遍历到一个节点然后将其左右儿子入栈
        {
            auto node=s.top().first;
            auto depth=s.top().second;
            s.pop();
            if(node->left==NULL && node->right==NULL)   //每到叶子节点更新
                result=min(result,depth);
            if(node->left && depth<result) //深度控制,剪枝,不用遍历到每一个节点
                s.push(make_pair(node->left,depth+1));
            if(node->right && depth<result)
                s.push(make_pair(node->right,depth+1));

        }
        return result;
    }

};

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-05 05:31:57

leetcode Minimum Depth of Binary Tree C++题解的相关文章

[leetcode]Minimum Depth of Binary Tree @ Python

原题地址:http://oj.leetcode.com/problems/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,树为空,

[leetcode] Minimum Depth of Binary Tree ,到叶子节点的最小距离 (python)

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. class Solution: # @param root, a tree node # @return an integer minDep =-1 def minDepth(se

LeetCode | Minimum Depth of Binary Tree

题目:给定一个二叉树,找到其最小深度.最小深度是从根节点到最近叶节点的最短路径的节点数. 1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 /** 11 最小深度为:根节点到达最近叶节点的最短路径 12 总体思想是:左子树

LeetCode Minimum Depth of Binary Tree 找最小深度(返回最小深度)

题意:找到离根结点最近的叶子结点的那一层(设同一层上的结点与根结点的距离相等),返回它所在的层数. 方法有: 1.递归深度搜索 2.层次搜索 方法一:递归(无优化) 1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL)

leetcode:Minimum Depth of Binary Tree【Python版】

1.类中递归调用添加self: 2.root为None,返回0 3.root不为None,root左右孩子为None,返回1 4.返回l和r最小深度,l和r初始为极大值: 1 # Definition for a binary tree node 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution:

Minimum Depth of Binary Tree leetcode java

题目: 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. 题解: 递归解法急速判断左右两边子树哪个depth最小,要注意如果有个节点只有一边孩子时,不能返回0,要返回另外一半边的depth. 递归解法: 1     public 

LeetCode: Maximum Depth of Binary Tree 题解

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 题解: 题意比较清楚, 找到从root出发最长的一条路径的长度. 采用DFS即可. 相似的一道题: Minimux Depth of Binary Tree 解法: http://

leetcode -day17 Path Sum I II &amp; Flatten Binary Tree to Linked List &amp; Minimum Depth of Binary Tree

1.  Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 r

【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

[LeetCode]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. 递归和非递归,此提比较简单.广度优先遍历即可.关键之处就在于如何保持访问深度. 下面是4种代码: 1