求二叉树的最大深度
此为有返回值的递归问题
先确定终止条件(如果一个树为空树,它的高度就是0,我们直接返回0,根本不用递归)
写出通式(1+max(左子树的最大深度,右子树的最大深度)规模更小的子问题),将通式写在return里面
1 int maxshendu(Node* node) { 2 if (node == nullptr) return 0; 3 return 1+max(maxshendu(node->left), maxshendu(node->right)); 4 }
此为有返回值的递归问题
先确定终止条件(如果一个树为空树,它的高度就是0,我们直接返回0,根本不用递归)
写出通式(1+max(左子树的最大深度,右子树的最大深度)规模更小的子问题),将通式写在return里面
1 int maxshendu(Node* node) { 2 if (node == nullptr) return 0; 3 return 1+max(maxshendu(node->left), maxshendu(node->right)); 4 }