about the diameter
the empty tree is represented by a null pointer, not by 0 in `val', the condition of the basic case should be
if(node)
for the recursion
The diameter of a tree is the number of nodes on the longest path between two leaves in the tree. |
you have three situations depending on where are the leaves of the diameter
- both on the left subtree
- both on the right subtree
- one on each subtree
so the check should be something like
1 2 3 4
|
ld = diameter(node->left)
rd = diameter(node->right)
both = depth(node->left) + depth(node->right) + 1
return max(ld, rd, both)
|
however, as you need to reach a leaf, `both' is only valid is no depth is 0
about your tree construction
1 2
|
if(ptr->left==NULL)
ptr->left=insert(0);
|
good noticing that a parent may appear later than its child on the input
however, when the loops ends you do
ptr=insert(temp);
. there are two errors there
first, you are creating an extra node
second, this last node is not linked to your tree
> I think it's because all the nodes are not being visited.
do a traversal and check it