07 二叉树的最小深度

📅 2026/7/4 10:28:01 👁️ 阅读次数 📝 编程学习
07 二叉树的最小深度

111. 二叉树的最小深度

已解答

简单

相关标签

premium lock icon相关企业

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

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

说明:叶子节点是指没有子节点的节点。

示例 1:

img

输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

提示:

  • 树中节点数的范围在 [0, 105]
  • -1000 <= Node.val <= 1000

class Solution {  //层序遍历
public:int minDepth(TreeNode* root) {int result=0;queue<TreeNode*> que;if(root!=NULL) {que.push(root);}while(!que.empty()){int size = que.size();//    vector<int> vec;while(size--){TreeNode* t = que.front();que.pop();// vec.push_back(t->val);if(t->left==NULL && t->right==NULL) return result+1;if(t->left) que.push(t->left);if(t->right) que.push(t->right);}result++;}return result;        }
};

class Solution {
public:int getDepth(TreeNode* node) {if (node == NULL) return 0;int leftDepth = getDepth(node->left);           // 左int rightDepth = getDepth(node->right);         // 右// 中// 当一个左子树为空,右不为空,这时并不是最低点if (node->left == NULL && node->right != NULL) { return 1 + rightDepth;}   // 当一个右子树为空,左不为空,这时并不是最低点if (node->left != NULL && node->right == NULL) { return 1 + leftDepth;}int result = 1 + min(leftDepth, rightDepth);return result;}int minDepth(TreeNode* root) {return getDepth(root);}
};
  • 注意这道题用的也是后序遍历,注意这道题中的深度被题目重定义了