您的位置:首页 > Web前端

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

2014-12-08 16:28 253 查看
题目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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: