You can do any of the inorder
, postorder
or preorder
traversals and calculate the height of each node. But for this problem instead of just calculating we insert the nodes in the data structure very similar to adjacency list
, the only difference being now linked list
at position 0
stores all the nodes with height = 0
, linked list
at position 1
stores all the nodes with height = 1
, and so on.
To get the output, we could simply print the elements each linked list starting from the first linked list
.
Following simple pseudocode does the job:
void inorderTraversal(NodePointer ptr)
{
if(ptr == NULL)
return;
else
{
inorderTraversal(ptr->left);
if(ptr->left == NULL and ptr->right == NULL)
{
ptr->height = 0;
adjacencyList[ptr->height].append(ptr->value);
}
else
{
if(ptr->left != NULL and ptr->right == NULL)
{
ptr->height = ptr->left->height + 1;
adjacencyList[ptr->height].append(ptr->value);
}
if(ptr->right != NULL and ptr->left == NULL)
{
ptr->height = ptr->right->height + 1;
adjacencyList[ptr->height].append(ptr->value);
}
if(ptr->right != NULL and ptr->left != NULL)
{
h1 = ptr->left->height;
h2 = ptr->right->height;
ptr->height = max(h1,h2)
adjacencyList[ptr->height].append(ptr->value);
}
}
inorderTraversal(ptr->right);
}
}
Now we can simply traverse all the linked lists
starting from the first linked list
and get the nodes in ascending order of their height.
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.