Posted on

Description

Submission

lmn: left most node

The crux here is using the index of each node and recording the index of the leftmost node

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        vector<unsigned long long> lmn;
        return dfs(root, 0, 0, lmn);
    }
private:
    int dfs(TreeNode* root, unsigned long long level, unsigned long long id, vector<unsigned long long>& lmn)
    {
        if(root == nullptr) return 0;
        if(level == lmn.size()) lmn.push_back(id);
        return max(int(id - lmn[level] + 1), 
                  max(dfs(root->left, level + 1, id * 2, lmn),
                     dfs(root->right, level + 1, id * 2 + 1, lmn)));
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *