把二元查找树转变成排序的双向链表
来源:互联网 发布:大疆一键全景软件下载 编辑:程序博客网 时间:2024/04/30 11:21
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4 = 6 = 8 = 10 = 12 = 14 = 16。
首先我们定义的二元查找树节点的数据结构如下:
struct BSTreeNode{int m_nValue; // value of nodeBSTreeNode *m_pLeft; // left child of nodeBSTreeNode *m_pRight; // right child of node};
我的解法:
中序遍历调整每个节点
只需要将当前结点连接至双向链表的最后一个结点,双向链表的最后一个结点连接至当前结点即可
Bst.h#pragma oncestruct BSTreeNode{int m_nValue; // value of nodeBSTreeNode *m_pLeft; // left child of nodeBSTreeNode *m_pRight; // right child of node};class Bst{public:Bst();~Bst();private:BSTreeNode* m_pRoot;//树根节点BSTreeNode* m_pHead;//指向链表头结点BSTreeNode* m_pTail;//指向当前链表最后一个节点void Bstinsert(BSTreeNode* &root, int iValue);//创建BSTvoid BstToDlist(BSTreeNode * root);//转换void changeNode(BSTreeNode* pCurrent);//改变节点指向void printDlist(BSTreeNode* head);//输出链表public:void insert(int value);//创建BSTvoid change();void show();};
Bst.cpp#include "Bst.h"#include<iostream>using namespace std;Bst::Bst(){m_pHead = NULL;m_pTail = NULL;m_pRoot = NULL;}Bst::~Bst(){}void Bst::Bstinsert(BSTreeNode *& root, int iValue){if (NULL == root){root = new BSTreeNode();root->m_nValue = iValue;root->m_pLeft = NULL;root->m_pRight = NULL;}else if (iValue > root->m_nValue){Bstinsert(root->m_pRight, iValue);}else if (iValue < root->m_nValue){Bstinsert(root->m_pLeft, iValue);}elsecout <<iValue<< "节点已存在"<<endl;}void Bst::BstToDlist(BSTreeNode * root){if (NULL == root){return;}BstToDlist(root->m_pLeft);changeNode(root);BstToDlist(root->m_pRight);}void Bst::changeNode(BSTreeNode * pCurrent){pCurrent->m_pLeft = m_pTail;//左孩子节点指向当前链表最后一个节点if (NULL == m_pTail){m_pHead = pCurrent;//创建头结点}else{m_pTail->m_pRight;//当前链表最后一个节点的右孩子节点指向当前节点}m_pTail = pCurrent;//调整m_pTail重新指向当前链表最后一个节点}void Bst::printDlist(BSTreeNode * head){if (head != NULL){cout << head->m_nValue << endl;printDlist(head->m_pRight);}}void Bst::insert(int value){Bstinsert(m_pRoot, value);}void Bst::change(){BstToDlist(m_pRoot);}void Bst::show(){printDlist(m_pHead);}
main.cpp#include<iostream>#include"Bst.h"using namespace std;void main(){Bst BstList;BstList.insert(4);BstList.insert(6);BstList.insert(8);BstList.insert(10);BstList.insert(12);BstList.insert(14);BstList.insert(16);BstList.change();BstList.show();}
0 0
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- .把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 安装Vmware tools
- 线程(1)---线程的状态(State)
- 基础总结篇之五:BroadcastReceiver应用详解
- git操作之同步分支
- 线程(1)----Thread的方法函数
- 把二元查找树转变成排序的双向链表
- 线程(1)----线程与进程
- 文件
- 线程(1)----线程停止
- 【西祠日志】【08】周五周五,一周又结束,有点困惑未了
- [Leetcode 229, Medium] Majority Element II
- 如何搭建Struts2项目
- Android开发笔记--WIFI状态判断
- Leetcode 7 Reverse Integer