The maximum width of the binary tree of data structure and algorithm (enhanced version)

The maximum width of the binary tree

topic

leetcode Original title source: 662. The maximum width of a binary tree - LeetCode

  • Given the root node of a binary tree, return the maximum width of the tree.
  • The maximum width of the tree is the largest width among all layers.
  • The width of each layer is defined as the length between the leftmost and rightmost non-empty nodes (ie, the two endpoints) of that layer. Think of this binary tree as the same structure as a full binary tree, there will be some null nodes extending to this level between the two ends, and these null nodes are also included in the length.
    insert image description here

train of thought

  • BFS+ number (full binary tree property)

    • According to the logic of layer order traversal, a queue is added to record the numbers of all nodes in the current layer. The formula for recording numbers is derived from the nature of full binary trees (you can push it yourself)
    • After each iteration (that is, all the nodes of the current layer have been traversed), it is necessary to compare the maximum width at this time. Here we assume that a variable is set to record the maximum width during initialization. Then in maxWidtheach At the end of the traversal, a comparison && update operation is required:maxWidth=Math.max(maxWidth,indexQueue.peeklast-indexQueue.peek+1);
    • Finally will maxWidthreturn to can.

Here is a video explanation: Leetcode 662 Hand-painted Graphic Edition|Maximum Width of Binary Tree_哔哩哔哩_bilibili

Code

    /**
 * 计算二叉树的最大宽度
 *
 * @param root 二叉树根节点
 * @return 最大宽度数
 */
public int widthOfBinaryTree(TreeNode root) {
    
    
    Deque<TreeNode> treeNodeQueue = new ArrayDeque<>();
    Deque<Integer> integerQueue = new ArrayDeque<>();
    int maxWidth = 0;
//        int curLevel = 1;
    treeNodeQueue.offer(root);
    integerQueue.offer(1);
    while (!treeNodeQueue.isEmpty() && !integerQueue.isEmpty()) {
    
    
        int size = treeNodeQueue.size();
//            curLevel++;
        while (size-- > 0) {
    
    
            TreeNode poll = treeNodeQueue.poll();
            Integer preIndex = integerQueue.poll();
            assert poll != null;
            assert preIndex != null;
            if (poll.left != null) {
    
    
                treeNodeQueue.offer(poll.left);
                integerQueue.offer(preIndex * 2);
            }
            if (poll.right != null) {
    
    
                treeNodeQueue.offer(poll.right);
                integerQueue.offer(preIndex * 2 + 1);
            }
        }
        if (!integerQueue.isEmpty()) {
    
    
            maxWidth = Math.max(maxWidth, integerQueue.peekLast() - integerQueue.peek() + 1);
        }
        //清空记录下标的队列
//            integerQueue.clear();
    }
    return maxWidth;
}

Guess you like

Origin blog.csdn.net/qq_45074341/article/details/126867879