• 二进制查找树转换为双向链表


    全然依照海涛哥剑指offer里边的递归思路来写的。基本一样。仅作学习验证。努力锻炼。努力学习!

    题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。要求不能创建不论什么新的结点,仅仅调整指针的指向。

      比方将二元查找树
        
                                            10
                                              /   
                                            6       14
                                          /       / 
                                        4     8  12    16
    转换成双向链表

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

    code例如以下:

    //Change a BSTree to a sorted double linklist
    struct BSTreeNode 
    {
    	int value;
    	BSTreeNode *left;
    	BSTreeNode *right;
    }head;
    //Create a node of BSTree for test
    BSTreeNode* CreateNode(int value)
    {
    	BSTreeNode *node = new BSTreeNode();
    	node->value = value;
    	node->left = NULL;
    	node->right = NULL;
    	return node;
    }
    //using a lastNode pointer to convert the pointer of the node
    void ConvertNode(BSTreeNode *head, BSTreeNode **lastNode)
    {
    	if(head == NULL)
    		return;
    	BSTreeNode *pCurrent = head;
    	if(pCurrent->left != NULL)
    		ConvertNode(pCurrent->left, lastNode);
    	pCurrent->left = *lastNode;
    	if(*lastNode != NULL)
    		(*lastNode)->right = pCurrent;
    	*lastNode = pCurrent;
    	if(pCurrent->right != NULL)
    		ConvertNode(pCurrent->right, lastNode);
    }
    //lastNode pointer is pointing to the rear,so the head can be obtained 
    BSTreeNode* Convert(BSTreeNode *head)
    {
    	if(head == NULL)
    		return NULL;
    	BSTreeNode *lastNode = NULL;
    	ConvertNode(head, &lastNode);
    	while(lastNode->left != NULL)
    		lastNode = lastNode->left;
    	return lastNode;
    }
    //main function for test
    int main()
    {
    	BSTreeNode *head = CreateNode(10);
    	head->left = CreateNode(8);
    	head->left->left = CreateNode(7);
    	head->left->right = CreateNode(9);
    	head->right = CreateNode(12);
    	head->right->left = CreateNode(11);
    	head = Convert(head);
    	while(head != NULL)
    	{
    		printf("%d ",head->value);
    		head = head->right;
    	}
    }


  • 相关阅读:
    记录一次腾讯云服务器进挖矿病毒的事故
    Django组件:django-simple-captcha 使用
    RabbitMQ延迟队列(Python版)
    RabbitMQ CLI 管理工具 rabbitmqadmin(管理)
    Django Rest Framework组件:用户访问次数/频率限制BaseThrottle
    GitLab 持续集成
    Windows10搭建Spark+Python开发环境
    Python 应用自动化部署工具Fabirc
    Prometheus:Prometheus开发中间件Exporter
    qs 和 headers: { "content-type": "application/x-www-form-urlencoded" }, data: qs.stringify(data) 必须同时设置
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6846599.html
Copyright © 2020-2023  润新知