剑指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; }
相关文章推荐
- python剑指offer系列二叉搜索树与双向链表
- 【剑指offer系列】 二叉搜索树与双向链表___27
- 剑指offer系列之二十五:二叉搜索树与双向链表
- 剑指offer系列源码-链表中倒数第k个结点
- 剑指offer系列源码-两个链表的第一个公共结点
- 剑指offer——面试题27:二叉搜索树与双向链表
- 《剑指offer》-将二叉搜索树转化为双向链表
- 剑指offer 之 二叉搜索树与双向链表
- 剑指offer系列源码-反转链表
- 《剑指offer》:[27]二叉搜索树与双向链表的转化过程
- 《剑指offer》-二叉搜索树与双向链表
- 剑指offer面试题27:二叉搜索树和双向链表
- 《剑指offer》(面试题27):二叉搜索树与双向链表
- 剑指offer-二叉搜索树与双向链表
- 《剑指offer》--二叉搜索树与双向链表
- 剑指Offer:面试题27 二叉搜索树与双向链表
- 剑指offer系列源码-复杂链表的复制
- 剑指offer-面试题27.二叉搜索树与双向链表
- 剑指offer:二叉搜索树与双向链表非递归与递归解法
- 剑指offer面试题-二叉搜索树转换成一个排序的双向链表