简体   繁体   English

AVL二进制搜索树中的节点列表,按其高度排序

[英]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? (从计算上)获取按其高度排序的AVL树中的节点列表的最佳方法是什么? For example with an AVL like this: 例如,使用这样的AVL: 例

The output should be: 输出应为:

[A, C, G, O, B, N, H, D] [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. 您可以进行任何inorderpostorderpreorder遍历,并计算每个节点的高度。 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. 但是对于这个问题,我们不只是计算节点,而是将节点插入数据结构中,与adjacency list非常相似,唯一的区别是position 0 linked list存储了所有height = 0的节点, position 1 linked list存储了所有节点的height = 0 height = 1 ,依此类推。

To get the output, we could simply print the elements each linked list starting from the first linked list . 为了获得输出,我们可以简单地从第一个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. 现在我们可以简单地从第一个linked list开始遍历所有linked lists ,并按其高度的升序获得节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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