写程序找出二叉树的深度。
一个树的深度等于max(左子树深度,右子树深度)+1。可以使用递归实现。
假设节点为定义为
struct Node {
Node* left;
Node* right;
};
int GetDepth(Node* root) {
if (NULL == root) {
return 0;
}
int left_depth = GetDepth(root->left);
int right_depth = GetDepth(root->right);
return left_depth > right_depth ? left_depth + 1 : right_depth + 1;
}