トピック説明:
バイナリツリーを考えると、ツリーの最大幅を取得する関数を記述します。幅は、すべてのツリー層の最大幅です。完全なバイナリツリー(完全なバイナリツリー)と同じ構造が、一部のノードを含むバイナリツリーは空です。
各層の幅の長さは、2つのエンドポイントとして定義されている間(非ヌル・ノードの左端と右端の層、二つの端点間のヌル・ノードはまた、長さが含まれます)。
この方法の一つ:
- 深さ優先順に、我々は、POSに各ノードを記録しました。各深さマップに記録される最初の位置に到達します。
- map.get(POS)+ 1 - 次に、この層の幅に対応する各ノードのためにPOSであってもよいです
- たびに、最大値はレコードの最大幅であります
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer,Integer> map=new HashMap<>();
int res=0;
public int widthOfBinaryTree(TreeNode root) {
func(root,0,0);
return res;
}
void func(TreeNode root,int height,int pos){
if(root!=null){
map.computeIfAbsent(height,value->pos);
res=Math.max(res,pos-map.get(height)+1);
func(root.left,height+1,pos*2);
func(root.right,height+1,pos*2+1);
}
}
}
方法2:
- バイナリツリーは、インデックスセット内に格納され、ルートインデックスは、* I + 1、ノード2の左サブツリー0であり、右の部分木は* I + 2 2標識。
- 次いで、最大幅とのそれぞれを識別するために、レベルを横切ります
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int widthOfBinaryTree(TreeNode root) {
if(root==null){
return 0;
}
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
List<Integer> list=new LinkedList<>();
list.add(0);
int max=1;
while(!q.isEmpty()){
int size=q.size();
for(int i=0;i<size;i++){
TreeNode tmp=q.poll();
int node=list.remove(0);
if(tmp.left!=null){
q.offer(tmp.left);
list.add(node*2+1);
}
if(tmp.right!=null){
q.offer(tmp.right);
list.add(node*2+2);
}
}
if(list.size()>=2){
max=Math.max(max,list.get(list.size()-1)-list.get(0)+1);
}
}
return max;
}
}