LeetCode 111. 二叉树的最小深度

    科技2025-05-06  54

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

    最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

    说明: 叶子节点是指没有子节点的节点。 分析:乍一看,我以为是和求二叉树的高度那种思想一样,返回的结果是二叉树左右子树最小高度+1,可是 忽略了左右子树可能有一方为空的情况,就是二叉树呈现单支的情况

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int minDepth(TreeNode* root) { if(root==NULL) return 0; //如果左子树为空,结果为右子树的最小深度+1 if(root->left==NULL) return 1+minDepth(root->right); //如果右子树为空,结果为左子树的最小深度+1 if(root->right == NULL) return 1+minDepth(root->left); //否则,为左右子树最小深度的最小值+1 int l = minDepth(root->left); int r = minDepth(root->right); return 1 + min(l,r); } };
    Processed: 0.016, SQL: 8