经典面试题目

从网上找了一些面试题目,做一做

/*1.把二元查找树转变成排序的双向链表(树)
 题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
   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 <cstdio>
#include <cstring>
using namespace std;
struct BSTreeNode
{
    int m_nValue;
    BSTreeNode *m_pLeft;
    BSTreeNode *m_pRight;
};
BSTreeNode *CreateNode(int v) //创建新节点
{
    BSTreeNode *pNew = new BSTreeNode();
    pNew->m_nValue = v;
    pNew->m_pLeft = pNew->m_pRight = NULL;
    return pNew;
}
void BSTBuild(BSTreeNode **pRoot, int v) //创建BST
{
    BSTreeNode *p = *pRoot;
    if(p == NULL){
        *pRoot = CreateNode(v);
    }else if(v < p->m_nValue){
        BSTBuild(&p->m_pLeft, v);
    }else BSTBuild(&p->m_pRight, v);
}
void BSTreeIn(BSTreeNode *pRoot) //BST中序遍历,输出为有序数列
{
    if(pRoot != NULL){
        BSTreeIn(pRoot->m_pLeft);
        printf("%d ", pRoot->m_nValue);
        BSTreeIn(pRoot->m_pRight);
    }
}
//BST转LIST,pRoot为当前根节点,nPre为当前节点的前驱结点,nRoot为链表的头结点
void BST2List(BSTreeNode *pRoot, BSTreeNode **nPre, BSTreeNode **nRoot)
{
    if(pRoot == NULL) return ;
    BST2List(pRoot->m_pLeft, nPre, nRoot);
    if(*nPre == NULL){      //最左边的节点为根节点
        *nRoot = pRoot;
    }else{                  //修改当前节点和前驱结点的指针
        (*nPre)->m_pRight = pRoot;
        pRoot->m_pLeft = *nPre;
    }
    *nPre = pRoot;          //将当前节点变为前驱结点,作为右子树节点的前驱
    BST2List(pRoot->m_pRight, nPre, nRoot);
}
void PrintList(BSTreeNode *pHead) //打印链表
{
    while(pHead){
        printf("%d ", pHead->m_nValue);
        pHead = pHead->m_pRight;
    }
}
int main()
{
    BSTreeNode *root = NULL;
    int n = 7;
    int a[] = {10, 6, 4, 8, 14, 12, 16};
    for(int i = 0; i < n; i++){
        BSTBuild(&root, a[i]);
    }
    BSTreeIn(root);
    printf("\n");
    BSTreeNode *nRoot = NULL, *nPre = NULL;
    BST2List(root, &nPre, &nRoot);
    PrintList(nRoot);
    printf("\n");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值