LeetCode 662. Maximum Width of Binary Tree
原题链接在这里:https://leetcode.com/problems/maximum-width-of-binary-tree/
题目:
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
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.
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).
Note: Answer will in the range of 32-bit signed integer.
题解:
把每个点笔记上id. cur.id = i, 那么cur.left.id = 2*i, cur.right.id = 2*i+1.
找到每一行开始点的id, start. 和最后点的id, end. 这一行的最大宽度就是end-start+1.
Time Complexity: O(n).
Space: O(n).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int widthOfBinaryTree(TreeNode root) { 12 if(root == null){ 13 return 0; 14 } 15 16 LinkedList<Combo> que = new LinkedList<>(); 17 que.add(new Combo(root, 1)); 18 int res = 1; 19 20 while(!que.isEmpty()){ 21 int size = que.size(); 22 int start = que.peek().id; 23 int end = start; 24 25 while(size-- > 0){ 26 Combo cur = que.poll(); 27 end = cur.id; 28 if(cur.node.left != null){ 29 que.add(new Combo(cur.node.left, cur.id * 2)); 30 } 31 32 if(cur.node.right != null){ 33 que.add(new Combo(cur.node.right, cur.id * 2 + 1)); 34 } 35 } 36 37 res = Math.max(res, end - start + 1); 38 } 39 40 return res; 41 } 42 } 43 44 class Combo{ 45 TreeNode node; 46 int id; 47 public Combo(TreeNode node, int id){ 48 this.node = node; 49 this.id = id; 50 } 51 }