简体   繁体   中英

maximum depth for a binary tree

Could someone explain the maxDepth() function, what value is being returned to ldepth and rdepth. How do the values increase for ldepth and rdepth with each recursion, I want to know which values are they storing. ldepth and rdepth were not even initialized with initial values. Do the values increment with every recursive process? I basically want to know the following two steps ldepth=maxDepth(node->left)); and rdepth=maxDepth(node->right));

#include<stdio.h>
#include<stdlib.h>

struct node
{
    int data;
    struct node *left;
    struct node *right;
};

int maxDepth(struct node *node)
{
    if(node==NULL)
    return 0;
    else
    {
        int ldepth;
        int rdepth;
        ldepth=maxDepth(node->left));
        rdepth=maxDepth(node->right));


        if(ldepth>rdepth)
        return (ldepth+1);
        else return (rdepth+1);
    }
}

struct node* newNode(int data)
{
    struct node* node=(struct node*)malloc(sizeof(struct node));
    node->data=data;
    node->left=NULL;
    node->right=NULL;
    return node;
}

 int main()
 {
     struct node *root=newNode(1);
    root->left=newNode(2);
    root->right=newNode(3);
    root->left->left=newNode(4);
    root->left->right=newNode(5);

    printf("Height of tree is %d",maxDepth(root));
    getchar();
    return 0;
}

Do the values increment with every recursive process?

Not exactly. The recursion goes deeper as long as there are child nodes. Once it satisfies 'if(node==NULL)', that is, there are no more leafs, it will return 0 to the calling node. Only then the value is incremented where it reaches 'return (ldepth+1);'

max depth takes root. root is node, its value is 1. As a node it has a left and a right node. the left node of root has also a left and a right node. so the tree looks like:

1 -> 2 -> 4
|    | -> 5
|--> 3 

maxDepth takes the element 1 it looks if the parameter is null, since 1 is not null it calls max depth for the left node 2 and the right node 3

lets focus on 2 now 2 is not null so it calls max depth for 4 and 5

lets focus on 4 now 4 is not null so it will call maxdepth for 4's left and right

4's left is NULL so it will return the value 0 now the function that calls the recursion continues (the maxDepth(4)) the value of ldepth is now 0

its increased by one and we fall back to the caller function maxDepth(2)

the depth is increased by 1

etc.

at the end we have the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM