1501 二叉树最大宽度和高度 (BFS+树的遍历)
题目:http://www.wikioi.com/problem/1501/
给你一颗二叉树,求该数的宽和高,
首先求出树的高,直接进行二叉树遍历,能够得到二叉树的高
然后是得到宽,本人采用的是一层一层的遍历,求出每一层节点的个数,最大的则是该树的宽了,
代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <stack> 4 #include <queue> 5 #include <iostream> 6 7 using namespace std; 8 9 #define L 1 10 #define R 2 11 class tree{ 12 private: 13 int a[20][3],h,w; 14 stack<int> mystack; 15 public: 16 tree(); 17 void set_tree(int i,int x,int y); 18 void tree_h(int i,int t);//得到高 19 void BFS(int t);//得到宽 20 int get_h(); 21 int get_w(); 22 }; 23 24 tree::tree() 25 { 26 memset(a,0,sizeof(a)); 27 h = 0; 28 w = 0; 29 } 30 31 void tree::set_tree(int i,int x,int y) 32 { 33 a[i][L] = x; 34 a[i][R] = y; 35 } 36 int tree::get_h() 37 { 38 int t = 1; 39 tree::tree_h(a[1][L],t+1); 40 tree::tree_h(a[1][R],t+1); 41 return h-1; 42 } 43 int tree::get_w() 44 { 45 mystack.push(1); 46 tree::BFS(1); 47 return w; 48 } 49 void tree::BFS(int i) 50 { 51 if(i <= h) 52 { 53 int t = 0,x; 54 stack<int> tmpstack; 55 while(mystack.empty() == false) 56 { 57 x = mystack.top(); 58 mystack.pop(); 59 if(x != 0) 60 { 61 t++; 62 tmpstack.push(a[x][L]); 63 tmpstack.push(a[x][R]); 64 } 65 } 66 67 w = w > t ? w : t; 68 mystack = tmpstack; 69 tree::BFS(i+1); 70 } 71 } 72 73 void tree::tree_h(int i,int t) 74 { 75 if(i == 0) 76 { 77 h = h > t ? h : t; 78 return; 79 } 80 else 81 { 82 tree::tree_h(a[i][L],t+1); 83 tree::tree_h(a[i][R],t+1); 84 } 85 } 86 int main() 87 { 88 int n,x,y; 89 while(~scanf("%d",&n)) 90 { 91 tree mytree; 92 for(int i = 1; i <= n; i++) 93 { 94 scanf("%d%d",&x,&y); 95 mytree.set_tree(i,x,y); 96 } 97 int h = mytree.get_h(); 98 int w = mytree.get_w(); 99 printf("%d %d\n",w,h); 100 } 101 return 0; 102 }
yy_room