二叉树的最小深度

来源:互联网 发布:厦门市公安局网络公章 编辑:程序博客网 时间:2024/04/30 15:48

题目描述:

给定一个二叉树,找出其最小深度。

二叉树的最小深度为根节点到最近叶子节点的距离。
样例

给出一棵如下的二叉树:

        1

     /     \ 

   2       3

          /    \

        4      5  

这个二叉树的最小深度为 2


解题思路:

和求解二叉树的最大深度类似,先判断根节点是否为空,若为空,返回0;再判断根节点的左子树和右子树是否为空,若同时为空,返回1;若左子树或者右子树其中之一为空,则求解不为空子树的最小深度,然后加1;若左子树和右子树都不为空,则比较左子树和右子树的最小深度,然后加1,得到二叉树的最小深度。

代码实现:

public:
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    int minDepth(TreeNode *root) {
        // write your code here
        if(root==NULL)
        return 0;
        if(root->left==NULL&&root->right==NULL)
        return 1;
        if(root->left==NULL)
        return minDepth(root->right)+1;
        if(root->right==NULL)
        return minDepth(root->left)+1;
        int leftDepth=minDepth(root->left);
        int rightDepth=minDepth(root->right);
        return leftDepth<rightDepth?(leftDepth+1):(rightDepth+1);
  }

感想:

求解最小深度,要从根节点多方面考虑,涉及到每一种情况的出现。

0 0
原创粉丝点击