662. Maximum Width of Binary Tree

粽子包子粿條發表於2020-12-10

Given a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

It is guaranteed that the answer will in the range of 32-bit signed integer.

Example 1:

Input: 

           1
         /   \
        3     2
       / \       \  
      5   3     9 

Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
Example 2:

Input: 

          1
         /  
        3    
       / \       
      5   3     

Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).
Example 3:

Input: 

          1
         / \
        3   2 
       /        
      5      

Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).
Example 4:

Input: 

          1
         / \
       3   2
       /     \  
      5     9 
     /         \
    6           7
Output: 8
Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).
 

Constraints:

The given binary tree will have between 1 and 3000 nodes.

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/maximum-width-of-binary-tree
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

層次遍歷,用一個map來儲存當前節點,以及它在的位置。位置指按陣列儲存樹的結構,所在的位置,即當前位置是i,那麼它的左右子樹,就是i * 2 與 i * 2 + 1。

class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<Pair<TreeNode, Integer>> queue = new ArrayDeque();
        queue.add(new Pair<>(root , 1));
        int result = 0;
        while (!queue.isEmpty()) {
            int levelNum = queue.size();
            Pair<TreeNode, Integer> pair = queue.peek();
// start表示這一層的最左的節點的位置
            int start = pair.getValue();
            int end;
            for (int i = 0; i < levelNum; i++) {
                Pair<TreeNode, Integer> node = queue.remove();
                TreeNode treeNode = node.getKey();
                int position = node.getValue();
// end表示這一層的最右的節點的位置
                end = position;
                if (treeNode.left != null) {
                    queue.add(new Pair<>(treeNode.left, position * 2));
                }
                if (treeNode.right != null) {
                    queue.add(new Pair<>(treeNode.right, position * 2 + 1));
                }

                result = Math.max(result, end - start + 1);
            }
        }
        return result;
    }
}

 

 

 

相關文章