题目链接:111. 二叉树的最小深度

题解:

求二叉树的深度问题!

题目简述:

求二叉树的最小深度!

题解:

**简单递归:**最小深度一定是左右子树中较小的一个,递归去处理,分几种情况:

  • 根节点为空:返回0
  • 左右子树都为空:返回1
  • 左右子树都非空:返回左右子树的较小深度加一
  • 左右子树一个空一个非空:返回该子树深度加一

时间复杂度:遍历每个节点一次,为O(n)

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 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) return 0;
if(!root->left && !root->right) return 1;
if(root->left && root->right) return min(minDepth(root->left), minDepth(root->right)) + 1;
if(root->left) return minDepth(root->left) + 1;
return minDepth(root->right) + 1;
}
};