转换二叉搜索树到链表

Converting binary search tree to linked list

本文关键字:链表 搜索树 转换      更新时间:2023-10-16

我正试图将二叉搜索树转换为链表。链表应该有较小的数字在前面,而较大的数字在后面(从最小到最大)。我需要创建一个函数,它接受一个二叉搜索树,并输出一个链表。

        4
      /   
     2     6
   /     / 
  1   3  5   7 

这是二叉搜索树。我需要这样做链表:1 2 3 4 5 6 7。下面是我当前的代码:

node<int>* makeLinkedList(binary_tree_node<int>* root_ptr);
int main()
{
    binary_tree_node<int> *s1 = sample1();  //Creates the tree
    node<int>* node1 = makeLinkedList(s1);  //invokes function to make a linked list
    //Loop to print out the values of the linked list
    for (node1; node1 != NULL; node1 = node1->link()){
        cout<<node1->data()<<endl;
    }
}
node<int>* makeLinkedList(binary_tree_node<int>* root_ptr){
    node<int>* left;
    if (root_ptr == NULL) {
            return NULL;
    }
    else{
        left = makeLinkedList(root_ptr->left()); 
        list_head_insert(left, root_ptr->data());  //list_head_insert inserts a new entry at the head of the linked list
        return left;
    }
}

当我运行代码时,输出是4,2,1。我就是不明白怎么把这个二叉搜索树转换成一个从最小到最大的链表。我试过把list_head_insert函数放在递归调用的顶部,但是输出什么也没有,列表是空的。

换句话说,你想让它在链表中排序

有一种遍历方法:序遍历。在这里看到的关于遍历的更多信息

那么如何做到这一点呢?作为提示,我将提供一个函数来按顺序"打印"这个BST的内容。这样你就可以开始工作了。(在弄清楚如何按顺序获取树的内容之后,您所要做的就是对列表调用插入函数)

void print_in_order(Node* t) {
    if(!t)
        return;
    print_in_order(t->left);
    cout << t->data;
    print_in_order(t->right);
}

class HeadAndTail<T> {
    LinkedListNode<T> head;
    LinkedListNode<T> tail;
    public HeadAndTail() {
        this.head = null;
        this.tail = null;
    }
}
public class Solution {
     public static LinkedListNode<Integer> constructLinkedList(BinaryTreeNode<Integer> root) {
        return construct(root).head;
    }
    public static HeadAndTail<Integer> construct(BinaryTreeNode<Integer> root) {
        if(root == null) {
            return new HeadAndTail<>();
        }
        if(isLeafNode(root)) {
            LinkedListNode<Integer> node = new LinkedListNode<>(root.data);
            HeadAndTail<Integer> headAndTail = new HeadAndTail<>();
            headAndTail.head = node;
            headAndTail.tail = node;
            return headAndTail;
        }
        LinkedListNode<Integer> node = new LinkedListNode<>(root.data);
        HeadAndTail<Integer> forLeftPart = construct(root.left);
        HeadAndTail<Integer> forRightPart = construct(root.right);
        node.next = forRightPart.head;
        HeadAndTail<Integer> headAndTail = new HeadAndTail<>();
        //if left part is null
        if(forLeftPart.tail != null) {
            forLeftPart.tail.next = node;
            headAndTail.head = forLeftPart.head;
        } else{
            headAndTail.head = node;
        }
        //if right part is null
        if(forRightPart.tail != null) {
            headAndTail.tail = forRightPart.tail;
        } else {
            headAndTail.tail = node;
        }
        return headAndTail;
    }

}