The maximum width of the binary tree

Topic Description:
Given a binary tree, write a function to get the maximum width of the tree. Width is the maximum width of all tree layers. The binary tree with full binary tree (full binary tree) the same structure, but some of the nodes is empty.

The length of the width of each layer is defined as two endpoints (the leftmost and rightmost layer of non-null node, null node between the two end points are also included length) between.

method one:

  • In the order of priority of depth, we recorded pos each node. For each depth reaches a first position will be recorded in the map.
  • Then, for each node, which corresponds to the width of this layer may be pos - map.get (pos) + 1
  • Each time the maximum value is the maximum width of the record
/**
 * 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);
        }
    }
}

Method Two:

  • The binary tree is stored in the index set, the root index is 0, a left subtree of node 2 * i + 1, the right subtree labeled 2 * i + 2.
  • The maximum width and then traverse the level, to identify each of
/**
 * 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;
    }
}
Published 163 original articles · won praise 13 · views 3778

Guess you like

Origin blog.csdn.net/qq_42174669/article/details/105018761