Leetcode 662. Maximum Width of Binary Tree

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/84944854

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Maximum Width of Binary Tree

2. Solution

/**
 * 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) {
        if(!root) {
            return 0;
        }
        vector<TreeNode*> level;
        root->val = 1;
        level.push_back(root);
        int maxWidth = 0;
        levelOrder(level, maxWidth);
        return maxWidth;
    }


private:
    void levelOrder(vector<TreeNode*> level, int& maxWidth) {
        maxWidth = max(maxWidth, level[level.size() - 1]->val - level[0]->val + 1);
        vector<TreeNode*> nextLevel;
        for(int i = 0; i < level.size(); i++) {
            TreeNode* current = level[i];
            if(current) {
                if(current->left) {
                    current->left->val = current->val * 2 - 1;
                    nextLevel.push_back(current->left);
                }
                if(current->right) {
                    current->right->val = current->val * 2;
                    nextLevel.push_back(current->right);
                }
            }
        }
        if(!nextLevel.empty()) {
            levelOrder(nextLevel, maxWidth);
        }
    }
};

Reference

  1. https://leetcode.com/problems/maximum-width-of-binary-tree/description/

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试