Convert Binary Search Tree to an Ordered Double Linked List

输入: 一棵二叉查找树

输出: 与二叉查找树对应的有序双向链表

要求:不允许额外生成节点,只允许调整指针指向。例如:
 

  10
  / /
  6   1
  / / / /
   4  8 12 16


要求变换后输出


4=6=8=10=12=14=16

 

个人思路:

考虑到对二叉排序树进行中序遍历可以实现元素的排序,不妨在中序遍历过程中实现对各个节点指针的调整。那么到底先动节点的左指针还是右指针呢?仔细思考一下,如果先动节点的右指针,在递归的过程中所有的右子树都会丢失。而先动左儿子指针的话,因为中序遍历是先左儿子,再根节点最后再右子树,这样一旦结束左子树的遍历,当前根节点的左儿子指针就不再需要了,因而可以通过左指针来记录中序遍历的顺序。这样将整棵树遍历一次后,就会形成一个以最大数为首节点的单向链表。为了产生双向链表, 需要将产生的单向链表再遍历一次,使得各节点的右儿子指针指向各自的前向节点。按照上述思路,算法的最坏时间复杂度为O(n)。

 

核心代码:

void BSTree::Inorder(BSTreeNode* &root) { if(root) { Inorder(root->left); root->left = prev; prev = root; Inorder(root->right); } } BSTreeNode* BSTree::ToDoubleLinkedList() { Inorder(root); BSTreeNode *p = Max(root), *q; while(p) { q = p->left; if(q == NULL) break; q->right = p; p = p ->left; } return p; }


以下C++代码完整实现建立二叉树,到链表的转换以及测试的过程。

#include <cstdlib> #include <ctime> #include <iostream> #include <set> using namespace std; /* private member access control and destructor are omitted in favor of simplicity */ struct BSTreeNode { BSTreeNode(int d = 0):data(d), left(0), right(0) {} int data; BSTreeNode *left, *right; }; struct BSTree { BSTree():root(0), prev(0) {} BSTreeNode* Insert(int d, BSTreeNode* &r); BSTreeNode* Max(BSTreeNode *r); void Inorder(BSTreeNode* &r); BSTreeNode* ToDoubleLinkedList(); BSTreeNode *root, *prev; }; BSTreeNode* BSTree::Insert(int d, BSTreeNode *&r) { if(r == NULL) return r = new BSTreeNode(d); if(r->data > d) return Insert(d, r->left); else return Insert(d, r->right); } BSTreeNode* BSTree::Max(BSTreeNode *root) { if(root == NULL) return NULL; while(root->right) root = root->right; return root; } /* in-order search on BST */ void BSTree::Inorder(BSTreeNode* &root) { if(root) { Inorder(root->left); root->left = prev; prev = root; Inorder(root->right); } } BSTreeNode* BSTree::ToDoubleLinkedList() { Inorder(root); BSTreeNode *p = Max(root), *q; while(p) { q = p->left; if(q == NULL) break; q->right = p; p = p ->left; } return p; } int main(void) { srand((unsigned)time(0)); /* 10 different random integers ranging from 0 to 99 */ set<int> s; for(int i = 0; i < 10; ++i) { int rd = rand() % 100; while(s.count(rd)) rd = rand() % 100; s.insert(rd); } /* build a Binary Search Tree */ BSTree tree; for(set<int>::const_iterator it = s.begin(); it != s.end(); ++it) { tree.Insert(*it, tree.root); } /* convert the Binary Search Tree to a Double Linked List */ BSTreeNode *p = tree.ToDoubleLinkedList(); /* linear search on the resulting list */ while(p) { cout << p->data << endl; p = p->right; } }


你可能感兴趣的:(list,tree,null,search,insert,destructor)