Finding the Depth of a Binary Tree
May 2, 2017 at 7:06am May 2, 2017 at 7:06am UTC
Hello, as the title states, I am trying to find the depth of an already created Binary Tree using the depth function below. I keep getting an error "invalid use of incomplete type struct node." Any help? Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
struct BinaryTree {
int item;
BinaryTree *left;
BinaryTree *right;
};
BinaryTree * newNode(int value){
BinaryTree *node=new BinaryTree;
node->item=value;
node->left=NULL;
node->right=NULL;
return (node);
}
int maxDepth(struct node* node) {
if (node==NULL) {
return (-1);
}
else {
// compute the depth of each subtree
int LDepth = maxDepth (node->left);
int RDepth = maxDepth (node->right);
// use the larger one
if (LDepth > RDepth)
return (LDepth +1);
else
return (RDepth +1);
}
}
int main( ){
struct BinaryTree *root;
int temp = 0;
root=newNode(3);
root->left=newNode(1);
root->right=newNode(5);
root->left->right=newNode(2);
root->right->left=newNode(4);
root->right->right=newNode(6);
temp = maxDepth(root);
}
May 2, 2017 at 9:10am May 2, 2017 at 9:10am UTC
Line 26: Change struct node
to BinaryTree
.
May 2, 2017 at 7:24pm May 2, 2017 at 7:24pm UTC
Shouldn't line 28 return 0 instead of -1? Right now a single node with no children will return a depth of 0 instead of 1.
Lines 35-39 might be clearer as
return 1+max(LDepth, RDepth);
Topic archived. No new replies allowed.