LeetCode111.二叉树最小深度
发布日期:2025-04-05 03:11:19 浏览次数:16 分类:精选文章

本文共 811 字,大约阅读时间需要 2 分钟。

递归条件:

  • 叶子节点的定义是左孩子和右孩子都为 null 时叫做叶子节点
  • 当 root 节点左右孩子都为空时,返回 1
  • 当 root 节点左右孩子有一个为空时,返回不为空的孩子节点的深度
  • 当 root 节点左右孩子都不为空时,返回左右孩子较小深度的节点值

/** * 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&&root->right==NULL)            return 1;        int left = minDepth(root->left);        int right = minDepth(root->right);        //这里其中一个节点为空,说明m1和m2有一个必然为0,所以可以返回left + right + 1;        if(root->left==NULL||root->right==NULL)            return left+right+1;        //左右孩子有一个为空,返回较小的那个        return min(left,right)+1;    }};

 

上一篇:LeetCode114.二叉树展开为链表[后序遍历典例]
下一篇:LeetCode110.平衡二叉树

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年05月13日 18时30分51秒