struct BSTreeNode //二分查找树中的一个节点
然后,我们就可以根据以上递归的思想一步一步写出c++源码了
BSTreeNode* ConvertNode(BSTreeNode* pNode, bool asRight)
{
}
最后,我们就可以用一个主函数来对以上一段程序进行包装,以形成一个独立功能的函数
BSTreeNode* Convert(BSTreeNode* pHeadOfTree)
{
}
思路之二是中序遍历二元查找树,由于中序遍历是从小到大遍历的,所以可以假设在遍历某一个子树的根节点的时候其左子树已经是一个排序双向链表了,并且如果再得到该双向链表的为指针,可以很轻易地将其与根节点相连,然后同样可以使得右子数成为一个排序双向链表,然后将根节点轻而易举的链接到右子数组成的排序双向链表.
//此函数的功能是将以pNode为根的树转换为排序双向链表,并且将她链接到以pLastNodeInList为已经调整好的双向链表的尾节点上
void ConvertNode(BSTreeNode*
pNode, BSTreeNode*& pLastNodeInList)
{
}
BSTreeNode* Convert_Solution1(BSTreeNode* pHeadOfTree)
{
}
将排序二叉树转化成双向链表,应该是一道很常见的面试题目,网上的实现比较多,有用递归也有用中序遍历法的。看到一位外国友人的实现,还是比较清晰的,思路如下:
This
is the core function to convert Tree to list. This function follows steps
1 and 2 of the above algorithm */node*
bintree2listUtil(node* root){ //
Base case if
(root == NULL) return
root; //
Convert the left subtree and link to root if
(root->left != NULL) { //
Convert the left subtree node*
left = bintree2listUtil(root->left); //
Find inorder predecessor. After this loop, left //
will point to the inorder predecessor for
(; left->right!=NULL; left=left->right); //
Make root as next of the predecessor left->right
= root; //
Make predecssor as previous of root root->left
= left; } //
Convert the right subtree and link to root if
(root->right!=NULL) { //
Convert the right subtree node*
right = bintree2listUtil(root->right); //
Find inorder successor. After this loop, right //
will point to the inorder successor for
(; right->left!=NULL; right = right->left); //
Make root as previous of successor right->left
= root; //
Make successor as next of root root->right
= right; } return
root;}//
The main function that first calls bintree2listUtil(), then follows step 3
//
of the above algorithmnode*
bintree2list(node *root){ //
Base case if
(root == NULL) return
root; //
Convert to DLL using bintree2listUtil() root
= bintree2listUtil(root); //
bintree2listUtil() returns root node of the converted //
DLL. We need pointer to the leftmost node which is //
head of the constructed DLL, so move to the leftmost node while
(root->left != NULL) root
= root->left; return
(root);
8942

被折叠的 条评论
为什么被折叠?



