二进制搜索树到链接列表转换仅转换一半条目

时间:2017-11-15 20:43:43

标签: c linked-list binary-search-tree

我有一个二叉搜索树:

                3
               / \
              1   6
                   \
                    17
                   /
                 15
                /  \ 
               13   15
              /
             6
              \
               12 
              /
             9

我的函数将BST转换为链接列表,其中root指向BST的根目录:

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr list,head;
    list = malloc(sizeof(struct ListNode));
    list->key = root->key;
    if (root->right != NULL)
    {
        list->next = convertBSTtoLinkedList(root->right);
    }
    if (root->left != NULL)  
    {
        head = convertBSTtoLinkedList(root->left);
        head->next = list;
        return head;
    }
    return list;
}

我已经手动完成了我的功能几个小时,无法看到我做错了什么。我已经确认我正在输入正确的BST。我的函数是打印出head指向链表开头的列表:

void printList(ListNodePtr head)
{
  while (head->next != NULL)
  {
    printf("%d ",(head->key));
    head = head->next;
  }
  printf("%d ",(head->key));
}

虽然我怀疑这个功能不正确。

我的预期输出是:

BST
1 3 6 6 9 12 13 15 15 17 
Linked list
1 3 6 6 9 12 13 15 15 17 

然而,出来的是:

BST
1 3 6 6 9 12 13 15 15 17 
Linked list
1 3 6 6 17 

1 个答案:

答案 0 :(得分:1)

当你得到最左边的树时,除了左边树的头部并将其指向当前节点之外的所有树。您想要走到该树的 end 并将结束指向当前节点。

if (root->left != NULL)  
{
    ListNodePtr tail;
    head = convertBSTtoLinkedList(root->left);
    tail = head;
    while (tail->next != NULL) {
        tail = tail->next;
    }
    tail->next = list;
    return head;
}

另外,对打印功能进行了一些小优化:

void printList(ListNodePtr head)
{
  while (head != NULL)
  {
    printf("%d ",(head->key));
    head = head->next;
  }
}