Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
题意:求出二叉树的最小深度
思路:
minDepth(root) = 1 + min(minDepth(root->left), minDepth(root->right));
但假设 root -> left 或 root->right为空时,minDepth对他们的计算结果为返回 0 ,所以这两个要分别处理一下。
复杂度: 时间O(n) 。空间O(log n)
int minDepth(const TreeNode *root){ if(!root) return 0; if(!root->left) return 1 + minDepth(root->right); if(!root->right) return 1 + minDepth(root->left); return 1 + min(minDepth(root->left), minDepth(root->right)); }