简体   繁体   中英

List of nodes in a AVL binary search tree, ordered by their height

What is the best way (computationally) to get a list of nodes in a AVL tree sorted by their height? For example with an AVL like this: 例

The output should be:

[A, C, G, O, B, N, H, D]

(No matter the order in case there are nodes of the same height)

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.

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