[LeetCode] 662. Maximum Width of Binary Tree

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.
在这里插入图片描述
在这里插入图片描述

解析

求解每一层中最左节点和最右节点之间的位置个数,即为每一层的宽度,然后计算最大的宽度,中间节点包括空节点。

解法1:递归

这个问题可以定义为求解每一层的起始节点位置以及最末节点位置,设定一个start数组来保存位置,由当前深度h可以得到当前层的节点数为2h-1,然后由当前节点的位置i可以计算得到左右节点的位置为2i和2i+1,由此可以递归左右子树。
如果当前节点为空直接返回;
判断当前深度是否大于start数组大小,如果大于说明到了新一层,把当前位置加入到start中;
用当前位置idx-start[h]+1来更新res;
递归左子树;
递归右子树。

class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        vector<int> start;
        int res = 0;
        helper(root, 0, 1, start, res);
        return res;
    }
    
    void helper(TreeNode* node, int h, int idx, vector<int>& start, int& res){
        if(!node) return;
        if (h >= start.size()) start.push_back(idx);
        res = max(res, idx-start[h]+1);
        helper(node->left, h + 1, idx * 2, start, res);
        helper(node->right, h + 1, idx * 2 + 1, start, res);
    }
};

直接用helper函数返回inx-start[h]+1, helper(left), helper(right)中的最大值。

class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        vector<int> start;
        return helper(root, 0, 1, start);
        
    }
    
    int helper(TreeNode* node, int h, int idx, vector<int>& start){
        if(!node) return 0;
        if (h >= start.size()) start.push_back(idx);
        return max({idx-start[h]+1, helper(node->left, h+1, idx*2, start), helper(node->right, h+1, idx*2 + 1, start)});
    }
};

解法2:层次遍历

建立一个queue,queue中存储的是要给pair<TreeNode*, int>,表示当前节点以及当前节点的位置。对于每一层,取队列头的节点的位置作为left,循环每一层计算right的位置,然后得到这一层的宽度。

class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        queue<pair<TreeNode*,int>> q;
        q.push({root, 1});
        while(!q.empty()){
            int size = q.size();
            int left = q.front().second;
            int right = left;
            for(int i=0;i<size;i++){
                TreeNode* p = q.front().first;
                right = q.front().second;
                q.pop();
                if(p->left) q.push({p->left, right*2});
                if(p->right) q.push({p->right, right*2+1});
            }
            res = max(res, right - left + 1);
        }
        return res;
    }
};

参考

http://www.cnblogs.com/grandyang/p/7538821.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值