Reputation: 130
I want to find a leaf node in an unsorted binary tree and be able to use it in other functions. i have this as an idea
UPDATED****
node * leaf(node* root)
{
if(root==NULL)
return NULL;
if(root->left==NULL && root->right==NULL)
return root;
else
{ leaf(root->left);
leaf(root->right);
}
}
Upvotes: 0
Views: 576
Reputation: 756
Try this:
If root has no children, then root is leaf node.
If root has left child, then the left child must have a leaf node. Same as right child.
node* leaf(node* root) {
if(root == NULL)
return NULL;
if(root->left == NULL && root->right == NULL) {
return root;
} else if(root->left != NULL) {
return leaf(root->left);
} else {
return leaf(root->right);
}
}
Upvotes: 1