LC 662. 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.

 

Runtime: 8 ms, faster than 28.24% of C++ online submissions for Maximum Width of Binary Tree.

 

看了一下更快的解法用的是递归,但是思路和我的是一样的。就是给每一个点都标上序号。

最快的解法竟然是用while嵌套BFS,看来递归花掉了很多时间,但我这个可能是由于有拷贝(nextq,q)。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
  int widthOfBinaryTree(TreeNode* root) {
    queue<pair<TreeNode*, int>> q;
    q.push({root, 1});
    int ret = 0;
    while(!q.empty()){
      int minval = INT_MAX, maxval = INT_MIN;
      queue<pair<TreeNode*,int>> nextq;
      while(!q.empty()){
        auto p = q.front(); q.pop();  
        minval = min(minval, p.second); maxval = max(maxval, p.second);
        if(p.first->left) nextq.push({p.first->left, 2*p.second});
        if(p.first->right) nextq.push({p.first->right, 2*p.second+1});
      }
      ret = max(ret, maxval - minval);
      q = nextq;
    }
    return ret+1;
  }
};

 

posted @ 2018-12-26 05:50  yuxihong  阅读(114)  评论(0编辑  收藏  举报