[剑指offer]面试题27 二叉搜索树与双向链表

来源:互联网 发布:iphone铃声软件哪个好 编辑:程序博客网 时间:2024/05/29 11:04

题目:输入一棵二叉搜索树,将该二叉搜素树转换成一个排序的双向链表。要求不能创建任何新的节点,只能调整书中节点指针的指向。

比如输入图4.12中左边的二叉搜索树,则输出转换之后的排序双向链表。

解题思路:书上感觉说的太罗嗦了,实质还是中序遍历树(当前节点为curNode),并记住每个节点的前一个节点(preNode),然后将curNode与preNode之间的链接调整好,OK.

代码如下:

#include <iostream>#include <stdlib.h>#include <time.h>using namespace std;struct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/*    function: insert the node into the binary search tree.*/void insertNode(TreeNode *&node, int num){    if(node == NULL){        node = new TreeNode(num);    }else{        if(node->val > num)            insertNode(node->left, num);        else if(node->val < num)            insertNode(node->right, num);        else            cout << "duplicate elements" << endl;    }}/*    function: display the node by inorder.*/void displayTree(TreeNode *node){    if(node != NULL){        displayTree(node->left);        cout << node->val << " ";        displayTree(node->right);    }}/*    function: display the current node and the previous node.*/void displayPre(TreeNode *curNode, TreeNode *&preNode){    if(curNode != NULL){        displayPre(curNode->left, preNode);        cout << curNode->val << " " ;        if(preNode != NULL)            cout << "PreNode:" << preNode->val << endl;        else            cout << endl;        preNode = curNode;        displayPre(curNode->right, preNode);    }}/*    function: convert the binary search tree to doublely linked list    question:         when void convertTreeToList(TreeNode *&curNode, TreeNode *&preNode),         error!! why??*/void convertTreeToList(TreeNode *curNode, TreeNode *&preNode){    if(curNode != NULL){        convertTreeToList(curNode->left, preNode);        if(preNode != NULL){            cout << "PreNode:" << preNode->val << endl;            preNode->right = curNode;            curNode->left = preNode;        }        preNode = curNode;        convertTreeToList(curNode->right, preNode);    }}int main(){    TreeNode *head = NULL;    srand(time(NULL));    //construct the tree    for(int i = 0;i < 10; i++)        insertNode(head, rand()%100);    displayTree(head);    cout << endl;    TreeNode *preNode = NULL;    convertTreeToList(head, preNode);    //head is still point the root    TreeNode *listHead = head;    //search the first node.    while(listHead ->left != NULL)        listHead = listHead->left;    cout << endl;    while(listHead != NULL){        cout << listHead->val << " ";        listHead = listHead->right;    }    return 0;}


0 0
原创粉丝点击