leetcode Minimum Depth of Binary Tree C++题解

来源:互联网 发布:36氪的next网站源码 编辑:程序博客网 时间:2024/04/29 09:53

题目描述

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;    }};
0 0