【树】655. 输出二叉树

题目:

解法:

方法一: 层次遍历+序号法

思路:对节点编号,根节点编号为i,从0开始,那么左子树为2i+1,右子树2i+2。

那么,每层的宽度 = 最后一个节点编号 – 第一个节点编号+1,编号不受空节点的影响。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     typedef unsigned long long ull;
13     int widthOfBinaryTree(TreeNode* root) 
14     {
15         if(!root) 
16         {
17             return 0;
18         }
19 
20         queue<TreeNode*> Q;
21         unordered_map<TreeNode*,long long> hash;
22         Q.push(root);
23         hash[root] = 0;
24         ull ans = 1;
25         while(Q.size())
26         {
27             int cnt = Q.size();
28             ull f;
29             for(int i = 0;i < cnt;++i)
30             {
31                 TreeNode* cur = Q.front();
32                 Q.pop();
33                 ull c = hash[cur];
34                 if(!i) 
35                 {
36                     f = c;
37                 }
38                 if(i == cnt-1) 
39                 {   
40                     ans = max(ans, c-f+1);
41                 }
42                 c *=2;
43                 
44                 if(cur->left) 
45                 {
46                     Q.push(cur->left);
47                     hash[cur->left] = c+1;
48                 }
49                 if(cur->right) 
50                 {
51                     Q.push(cur->right);
52                     hash[cur->right] = c+2;
53                 }
54             }
55         }
56         return ans;
57     }
58 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12821925.html