zoukankan      html  css  js  c++  java
  • UVA 548 tree(尽量多的方法做吧~~~)

    废话不说,先贴代码。
    总结一下:
    1::链表什么的,left,rigit,不是想当然它就那么自然的连接下面的。 要自己申请空间给root->left,root->right
    2::求和放在dfs里面
    3::以后若是有比赛的环境,ANSI C可能不允许用//,得注意点...
    4::还有看清题目要求开数组
    1
    #include<cstdio> 2 #include<string> 3 #include<vector> 4 #define maxn 10010//得比10000大 5 using namespace std; 6 vector<int>ans; 7 int innode[maxn];int postnode[maxn]; 8 typedef struct Node 9 { 10 struct Node *left; 11 struct Node *right; 12 int data; 13 }node; 14 int nodeIndex; 15 node cc[maxn]; 16 node * newnode() 17 { 18 /*node *u=new node; 19 u->left=NULL; 20 u->right=NULL; 21 return u;*/ 22 cc[nodeIndex].left = NULL; 23 cc[nodeIndex].right = NULL; 24 return &cc[nodeIndex++]; 25 } 26 node* buildtree(int innode[],int postnode[],int len) 27 { 28 if(len==0) return NULL; 29 int i=len-1; 30 while(postnode[len-1]!=innode[i]) 31 --i; 32 node *h=newnode();//这地方往下都是自己没写出来的 //这里应该得自己申请一个空间吧 33 h->data=postnode[len-1]; 34 h->left=buildtree(innode,postnode,i); 35 h->right=buildtree(innode+i+1,postnode+i,len-i-1); 36 return h; 37 } 38 void dfs(node *root,int n)//结点求和加在dfs里面了... 39 { 40 if(root->left==NULL&&root->right==NULL) 41 { 42 ans.push_back(n+root->data);return;//这地方得有return 不然这个递归就没有结束条件了 43 } 44 while(root->left!=NULL) dfs(root->left,n+root->data); 45 while(root->right!=NULL) dfs(root->right,n+root->data); 46 } 47 int main() 48 { 49 freopen("input.txt","r",stdin); 50 //freopen("output.txt","w",stdout); 51 while(scanf("%d",&innode[0])!=EOF)//这个地方输入挺特别的 先读取第一位 然后由中序遍历的长度读取后序遍历 52 { 53 ans.clear();//每次ans得清零 54 int t=1; 55 while(getchar()!='\n')//这个地方的处理也值得自己学习 当输入不是回车时才读入整数.... 56 scanf("%d",&innode[t++]);//这样可以根据t来处理后序遍历 也不用保存字符了....赞 57 for(int i=0;i<t;i++) 58 scanf("%d",&postnode[i]); 59 node *root=buildtree(innode,postnode,t); 60 dfs(root,0);//把求和这一步要加在dfs里面比较好吧 61 int temp=ans[0]; 62 for(int j=0;j<ans.size();j++) 63 if(temp>ans[j]) temp=ans[j]; 64 printf("%d\n",temp); 65 } 66 return 0; 67 }
  • 相关阅读:
    Best Time to Buy and Sell Stock III
    Valid Palindrome
    Longest Substring Without Repeating Characters
    Copy List with Random Pointer
    Add Two Numbers
    Recover Binary Search Tree
    Anagrams
    ZigZag Conversion
    Merge k Sorted Lists
    Distinct Subsequences
  • 原文地址:https://www.cnblogs.com/cgf1993/p/2922669.html
Copyright © 2011-2022 走看看