二叉树的最小深度

Sandals-little / 2023-08-03 / 原文

所以,如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。

反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。

 1 int minshendu(Node* node) {
 2     if (node == nullptr) return 0;
 3     if (node->left == nullptr && node->right != nullptr) {
 4         return 1 + minshendu(node->right);
 5     }
 6     if (node->left != nullptr && node->right == nullptr) {
 7         return 1 + minshendu(node->left);
 8     }
 9     return 1 + min(minshendu(node->left), minshendu(node->right));
10 }