转换二叉搜索树到链表
Converting binary search tree to linked list
我正试图将二叉搜索树转换为链表。链表应该有较小的数字在前面,而较大的数字在后面(从最小到最大)。我需要创建一个函数,它接受一个二叉搜索树,并输出一个链表。
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;
}
}
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 为什么当我尝试搜索双链表中第一个数据条目之外的数据时,程序崩溃了?
- Sinlge 链表,C++,删除所有和搜索功能的问题
- 将二叉树的节点插入链表 (C++)
- 这是在传递 int num 时创建搜索函数的正确方法吗?使用链表库
- 快速搜索链表未编译,需要返回语句
- ASAN:将二叉树平展为链表时释放后堆使用
- 搜索链表时出现隔离错误
- 访问链表中的结构(带有指向其子实现的指针列表的树)
- 双向链表插入方法实现 - 正在搜索哪个节点
- 将二进制树更改为双链表的程序
- 为什么我的代码无法在二叉搜索树中正确执行预购表单?
- 不太确定如何从这里继续前进.是否使用链表进行搜索
- C++有序链表搜索函数算法逻辑
- 将节点插入二进制搜索树/链表
- C++链表搜索错误:STATUS_ACCESS_VIOLATION
- 转换二叉搜索树到链表
- 当条目以有序的方式添加时,二叉搜索树有效地充当链表
- 是链表、树等的递归析构函数
- 有序双链表搜索