Maximum Width of Binary Tree

2019-05-25 22:39:26 浏览数 (1)

1. Description

2. Solution

代码语言:javascript复制
/**
 * 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);
        }
    }
};

0 人点赞