LeetCode111 Minimum Depth of Binary Tree
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. (Easy)
分析:
注意题目中定义的最短深度是从根节点到叶子节点的最短长度。所以到空节点返回0,且当有一个子节点为空,另一个不空时,那个点不是叶子节点,不能算作最深的一层。
代码:
1 class Solution { 2 public: 3 int minDepth(TreeNode* root) { 4 if (root == nullptr) { 5 return 0; 6 } 7 if (root -> left != nullptr && root -> right != nullptr) { 8 return min(minDepth(root->left), minDepth(root->right)) + 1; 9 } 10 else if (root -> left != nullptr) { 11 return minDepth(root->left) + 1; 12 } 13 return minDepth(root -> right) + 1; 14 15 } 16 };