剑指offer系列源码-二叉搜索树与双向链表

题目1503:二叉搜索树与双向链表
时间限制:1 秒内存限制:128 兆特殊判题:否提交:870解决:228
题目描述:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
输入:
输入可能包含多个测试样例。
对于每个测试案例,输入的第一行为一个数n(0<n<1000),代表测试样例的个数。
接下来的n行,每行为一个二叉搜索树的先序遍历序列,其中左右子树若为空则用0代替。
输出:
对应每个测试案例,
输出将二叉搜索树转换成排序的双向链表后,从链表头至链表尾的遍历结果。
样例输入:
1
2 1 0 0 3 0 0
样例输出:
1 2 3

#include <iostream>
#include<stdio.h>
using namespace std;
struct BinaryTreeNode{
    int value;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
};
void createTree(BinaryTreeNode*& root){
    int m;
    scanf("%d",&m);
    if(m==0){
        root = NULL;
    }else{
        BinaryTreeNode* pNode = new BinaryTreeNode();
        pNode->value = m;
        pNode->left = NULL;
        pNode->right = NULL;
        root = pNode;
        createTree(root->left);
        createTree(root->right);
    }
}
void printPreOrderTree(BinaryTreeNode* root){
    if(root==NULL){
        return;
    }
    if(root->left){
        printPreOrderTree(root->left);
    }
    if(root)
    printf("%d ",root->value);
    if(root->right){
        printPreOrderTree(root->right);
    }
}
int main(){
    int n;
    scanf("%d",&n);
    while(n--){
        BinaryTreeNode* root;
        createTree(root);
        printPreOrderTree(root);
        printf("\n");
    }
    return 0;
}
#include <iostream>
#include<stdio.h>
using namespace std;
struct BinaryTreeNode{
    int value;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
};
void convertNode(BinaryTreeNode* root,BinaryTreeNode*& pLastNodeInList){
    if(root==NULL)return;
    BinaryTreeNode* pCurrent = root;
    if(pCurrent->left){
        convertNode(pCurrent->left,pLastNodeInList);
    }
    pCurrent->left = pLastNodeInList;
    if(pLastNodeInList){
        pLastNodeInList->right = pCurrent;
    }
    pLastNodeInList = pCurrent;
    if(pCurrent->right){
        convertNode(pCurrent->right,pLastNodeInList);
    }

}
BinaryTreeNode* convert(BinaryTreeNode* root){
        BinaryTreeNode* pLastNodeInList = NULL;
        //关键
        convertNode(root,&pLastNodeInList);
        //返回头节点
        BinaryTreeNode* pHeadOfList = pLastNodeInList;
        while(pHeadOfList&&pHeadOfList->left!=NULL){
            pHeadOfList = pHeadOfList->left;
        }
        return pHeadOfList;
}
int main(){
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值