二叉树的最小深度

    xiaoxiao2021-04-15  60

    1.问题描述:给定一个二叉树,找出其最小深度。二叉树的最小深度为根节点到最近叶子节点的距离。

    2.思路:正如样例

    给出一棵如下的二叉树:

            1

         /     \ 

       2       3

              /    \

            4      5  

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

    利用递归的思想,不断求左右子树的最小深度,两者中最小的+1即为该二叉树的最小深度。但是一定要注意左右子树为空的情况!!!

    3.代码:

    /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { 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) return minDepth(root->right)+1; if(root->right==NULL) return minDepth(root->left)+1; else{int l=minDepth(root->left); int r=minDepth(root->right); if(l<r) return l+1; else return r+1;} } };

    4.感想:开始我就按求二叉树的最大深度的思想运行这个程序,结果显示wa.忽略了左子树或者右子树为空的情况。

    转载请注明原文地址: https://ju.6miu.com/read-670763.html

    最新回复(0)