2006年清华大学计算机研究生机试真题
2012-02-26 20:07
369 查看
http://ac.jobdu.com/problem.php?pid=1078
二叉树遍历
二叉树遍历
#include<stdio.h> #include<string.h> //二叉树结点的描述 typedef struct BinaryTreeNode { char data; struct BinaryTreeNode *lchild, *rchild; //左右孩子 }BinaryTreeNode,*BinaryTree; inline BinaryTreeNode* ConstructCore(char *startPreorder, char *endPreorder, char *startInorder, char *endInorder) { //前序遍历序列的第一个字符是根节点的值 char rootValue = startPreorder[0]; BinaryTreeNode* root = new BinaryTreeNode(); root->data = rootValue; root->lchild = root->rchild = NULL; if(startPreorder == endPreorder) { if(startInorder == endInorder && *startPreorder== *startInorder) return root; } //在中序遍历中找到根节点的值 char *rootInorder = startInorder; while(rootInorder <= endInorder && *rootInorder != rootValue) rootInorder++; int leftLength = rootInorder - startInorder; char *leftPreorderEnd = startPreorder + leftLength; if(leftLength > 0) { //构建左子树 root->lchild = ConstructCore(startPreorder+1, leftPreorderEnd, startInorder, rootInorder-1); } if(leftLength < endPreorder - startPreorder) { //构建右子树 root->rchild = ConstructCore(leftPreorderEnd+1, endPreorder, rootInorder+1, endInorder); } return root; } //分别在前序遍历和中序遍历的序列中确定左、右子树的子序列 inline BinaryTreeNode* Construct(char *preorder, char *inorder, int length) { if(preorder == NULL || inorder == NULL || length<=0) return NULL; return ConstructCore(preorder, preorder+length-1, inorder, inorder+length-1); } //后序遍历 inline void PostOrder(BinaryTreeNode *root) { if(root==NULL) return ; PostOrder(root->lchild); //递归调用,前序遍历左子树 PostOrder(root->rchild); //递归调用,前序遍历右子树 printf("%c", root->data); //输出数据 } //释放二叉树 inline void DeleteBinaryTree(BinaryTree root) { if(root) { DeleteBinaryTree(root->lchild); //释放左子树 DeleteBinaryTree(root->rchild); //释放右子树 delete root; //释放根结点 } } int main(void) { int length; char preorder[27],inorder[27]; while(scanf("%s",preorder)!=EOF) { scanf("%s",inorder); length = strlen(preorder); BinaryTreeNode* root = Construct(preorder, inorder, length); PostOrder(root); printf("\n"); DeleteBinaryTree(root); } return 0; }
相关文章推荐
- 2006年清华大学计算机研究生机试真题
- 题目1078:二叉树遍历(2006年清华大学计算机研究生机试真题)
- 题目1076:N的阶乘(2006年清华大学计算机研究生机试真题)
- 2003年清华大学计算机研究生机试真题之五
- 2011年清华大学计算机研究生机试真题
- 机试:成绩排序(2000年清华大学计算机研究生机试真题)
- 还是畅通工程 2006年浙江大学计算机及软件工程研究生机试真题
- 题目1207:质因数的个数(2007年清华大学计算机研究生机试真题)
- 题目1017:还是畅通工程(2006年浙江大学计算机及软件工程研究生机试真题)
- 2000年清华大学计算机研究生机试真题
- 2008年清华大学计算机研究生机试真题
- 九度OJ 1019 简单计算器 -- 2006年浙江大学计算机及软件工程研究生机试真题
- 2006年上海交通大学计算机研究生机试真题
- 题目1065:输出梯形(2001年清华大学计算机研究生机试真题(第II套))
- 九度OJ 1019 简单计算器 -- 2006年浙江大学计算机及软件工程研究生机试真题
- 题目1065:输出梯形(2001年清华大学计算机研究生机试真题(第II套))
- 2000年清华大学计算机研究生机试真题(Java自定义容器类的排序)
- 统计同成绩学生人数 2006年浙江大学计算机及软件工程研究生机试真题
- 2000年清华大学计算机研究生机试真题
- 2006年浙江大学计算机及软件工程研究生机试真题