zoukankan      html  css  js  c++  java
  • 把二元查找树转变成排序的双向链表

    /*

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

    10
    /
    6 14
    / /
    4 8 12 16

    转换成双向链表
    4=6=8=10=12=14=16。

    首先我们定义的二元查找树 节点的数据结构如下:
    struct BSTreeNode
    {
    int m_nValue; // value of node
    BSTreeNode *m_pLeft; // left child of node
    BSTreeNode *m_pRight; // right child of node
    };*/

    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    struct BSTreeNode
    {
    	int m_nValue; // value of node
    	BSTreeNode *m_pLeft; // left child of node
    	BSTreeNode *m_pRight; // right child of node
    };
    
    typedef BSTreeNode DoubleList;
    DoubleList *pHead;
    DoubleList *pListIndex;
    
    void convertToDoubList(BSTreeNode *pCurrent);
    
    //创建二叉树
    void addBSTreeNode(BSTreeNode *&pCurrent,int value)
    {
    	
                      //如果树节点为NULL,创建新的节点
                      if (pCurrent == NULL)
    	{
    		BSTreeNode *BSNode = new BSTreeNode();
    		BSNode->m_pRight = NULL;
    		BSNode->m_pLeft = NULL;
    		BSNode->m_nValue = value;
    		pCurrent = BSNode;
    	}else
    	{	
    		if(pCurrent->m_nValue > value)
    		{
    			addBSTreeNode(pCurrent->m_pLeft,value);
    		}else 
    		{
    			addBSTreeNode(pCurrent->m_pRight,value);
    		}
    	}
    }
    //中序遍历,相当于一个排序算法,先遍历左子树,在遍历根节点,最后遍历右子树
    void ergodicBSTree(BSTreeNode *pCurrent)
    {
    	if (pCurrent != NULL)
    	{
    		ergodicBSTree(pCurrent->m_pLeft);
    		 convertToDoubList(pCurrent);
    		//cout << pCurrent->m_nValue;
    		//cout << " ";
    		ergodicBSTree(pCurrent->m_pRight);
    	
    	}
    }
    void convertToDoubList(BSTreeNode *pCurrent)
    {
    	pCurrent->m_pLeft = pListIndex;
    	if (NULL != pListIndex)
    	{
    		pListIndex->m_pRight = pCurrent;//双向的~
    	}else
    	{
    		pHead = pCurrent;
    	}
    	pListIndex = pCurrent;
    	cout << pCurrent->m_nValue << " ";
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	BSTreeNode *mRoot = NULL;
    	addBSTreeNode(mRoot,10);
    	addBSTreeNode(mRoot,8);
    	addBSTreeNode(mRoot,6);
    	addBSTreeNode(mRoot,4);
    	addBSTreeNode(mRoot,12);
    	addBSTreeNode(mRoot,14);
    	addBSTreeNode(mRoot,16);
    	ergodicBSTree(mRoot);
    	system("pause");
    	return 0;
    }
    
  • 相关阅读:
    Redis源代码分析(十三)--- redis-benchmark性能測试
    kvm中运行kvm
    umount.nfs device busy day virsh extend diskSpace, attachDisk
    ultravnc
    openNebula dubug
    maintenance ShellScripts
    virsh VMI deploy data serial xml
    cloud computing platform,virtual authentication encryption
    基于C 的libvirt 接口调用
    storage theory
  • 原文地址:https://www.cnblogs.com/study-programmer/p/3406598.html
Copyright © 2011-2022 走看看