2006年清华大学计算机研究生机试真题
生活随笔
收集整理的這篇文章主要介紹了
2006年清华大学计算机研究生机试真题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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年清华大学计算机研究生机试真题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STL快速解题
- 下一篇: 2007年浙江大学计算机及软件工程研究生