The node structure of a known binary tree is defined as follows:
typedef struct NODE
{
int data;
struct NODE *lch, *rch;
} NODE;
Description: data
It is a data field. lch
and are rch
pointers to the left and right children, respectively.
Please write a function to find the depth of a binary tree.
function prototype
int Depth(const NODE *root);
Description: root
It is the root pointer of the binary tree, and the function value is the depth of the binary tree.
referee procedure
int main()
{
NODE *root;
Create(&root);
Input(&root);
printf("%d\n", Depth(root));
printf("%d\n", Depth(root));
Destroy(&root);
return 0;
}
Explanation: The Create function creates an empty binary tree, and the Destroy function destroys the binary tree. The Input function inputs the binary tree in root-first traversal order, and the node values are all positive integers, and zero is input when an empty tree is encountered.
input sample
85 37 94 53 0 0 21 0 0 0 18 46 0 60 0 0 9 0 72 0 0
output sample
4
4
int Depth(const NODE *root)
{
int dep1, dep2;
if (root == NULL)
return 0;
else
{
dep1 = Depth(root->lch);//递归调用左子树
dep2 = Depth(root->rch);//递归调用右子树
return dep1 > dep2 ? dep1 + 1 : dep2 + 1;
//返回两者中最大的值
}
}