递归实现深搜
错误代码:
int minDepth(TreeNode* root) {
if(NULL == root)
return 0;
return 1 + min(minDepth(root->left), minDepth(root->right));
}
错误原因:
当仅有一个子树为空时,子树的深度不是取最小的0,而是另一个非空子树的深度。
正确代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
if root.left is None:
return 1 + self.minDepth(root.right)
elif root.right is None:
return 1 + self.minDepth(root.left)
else:
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
int minDepth(TreeNode* root) {
if(NULL == root)
return 0;
if(NULL==root->left || NULL==root->right)
return 1+minDepth(root->left)+minDepth(root->right);
return 1 + min(minDepth(root->left), minDepth(root->right));
}