662 二叉樹最大寬度
阿新 • • 發佈:2020-12-18
技術標籤:LeetCode
題目描述:
給定一個二叉樹,編寫一個函式來獲取這個樹的最大寬度。樹的寬度是所有層中的最大寬度。這個二叉樹與滿二叉樹(full binary tree)結構相同,但一些節點為空。
每一層的寬度被定義為兩個端點(該層最左和最右的非空節點,兩端點間的null節點也計入長度)之間的長度。
示例 1:
輸入:
輸出: 4
解釋: 最大值出現在樹的第 3 層,寬度為 4 (5,3,null,9)。
示例 2:
輸入:
輸出: 2
解釋: 最大值出現在樹的第 3 層,寬度為 2 (5,3)。
示例 3:
輸入:
輸出: 2
解釋: 最大值出現在樹的第 2 層,寬度為 2 (3,2)。
示例 4:
輸入:
輸出: 8
解釋: 最大值出現在樹的第 4 層,寬度為 8 (6,null,null,null,null,null,null,7)。
注意: 答案在32位有符號整數的表示範圍內。
方法1:
主要思路:解題彙總連結
(1)使用層次遍歷,將根節點標識一個數字n,則對應的左子樹為 2n-1,對應的右子樹為 2n;
(2)將整個樹的根標識為1,則在層次遍歷過程中,儲存對應子樹時,同時儲存標識數字;
(3)在遍歷每層時,計算該層的寬度,儲存最大寬度;
(4)為了避免標識數字的越界,這裡使用了unsigned long;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
queue<pair<TreeNode*,unsigned long >> q;
q.push({root,1});//初始化佇列
int res=0;
while(!q.empty()){
int size_cur=q.size();//當前層的結點數量
unsigned long left_index=q.front().second; //最左邊的結點標識
unsigned long index=0;//遍歷該層的各個結點的標識
while(size_cur--){//遍歷當前層
index=q.front().second;//獲得結點標識
TreeNode* cur_node=q.front().first;//獲得結點指標
q.pop();
if(cur_node->left){
q.push({cur_node->left,2*index-1});//儲存左子樹,及對應的標識
}
if(cur_node->right){
q.push({cur_node->right,2*index});//儲存右子樹,及對應的標識
}
}
res=res<index-left_index+1?index-left_index+1:res;//更新當前層的寬度
}
return res;
}
};
方法2:
主要思路:
(1)為了避免標識數字的越界,觀察每層的結點的相對位置不變即可,則對每層的標識數字,可以將最左邊的數字減小到1,該層的其他結點對應的減小即可;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
queue<pair<TreeNode*,int>> q;
q.push({root,1});
int res=0;
while(!q.empty()){
int size_cur=q.size();
int left_index=q.front().second;
int diff_index=left_index*2-2;//需要減小的差值
int index=0;
while(size_cur--){
index=q.front().second;
TreeNode* cur_node=q.front().first;
q.pop();
if(cur_node->left){
q.push({cur_node->left,2*index-1-diff_index});//同時減去差值,保證相對位置一致
}
if(cur_node->right){
q.push({cur_node->right,2*index-diff_index});
}
}
res=res<index-left_index+1?index-left_index+1:res;
}
return res;
}
};