算法
采用递归的方法
1.如果左子树不为空,递归计算左子树的深度left
2.如果右子树不为空,递归计算右子树的深度right
3.比较left和right,树的深度为较大者+1(加上根结点)
代码
//计算整个树的深度
int maxDepth(){
return maxDepth(root);
}
//计算指定子树的深度
int maxDepth(Node<Value>* x){
int depth = 0;
int left = 0;
int right = 0;
//计算左子树深度
if(x->left != nullptr) left = maxDepth(x->left);
//计算右子树深度
if(x->right != nullptr) right = maxDepth(x->right);
//比较左右子树的深度,较大者+1为整个子树的深度
depth = left > right ? left + 1 : right + 1;
return depth;
}