Leetcode#662. Maximum Width of Binary Tree

本文介绍了一种求解二叉树最大宽度的有效算法。通过递归和非递归两种方式实现了该算法,并详细展示了使用C++编程语言的具体实现过程。

题目描述:求二叉树的最大宽度

class Solution {
public:
    void DFS(TreeNode* root, int depth, int index, vector<int> &start, int &maxWidth)
    {
        if(root == NULL)
            return;
        else
        {
            if(depth >= start.size())
                start.push_back(index);
            maxWidth = max(maxWidth, index - start[depth] + 1);
            DFS(root->left, depth + 1, 2 * index, start, maxWidth);
            DFS(root->right, depth + 1, 2 * index + 1, start, maxWidth);
        }
    }
    int widthOfBinaryTree(TreeNode* root) {
        int maxWidth = 0;
        vector<int> start;
        DFS(root, 0 , 1, start, maxWidth);
        return maxWidth;
    }
};

20180816更新,非递归实现

class Solution{
public:
    int widthOfBinaryTree(TreeNode *root){
        if(root == NULL)
        { 
            return 0; 
        }
        if(root->left == NULL && root->right == NULL)
        { 
            return 1; 
        }

        int max_width = 1;
        deque<pair<TreeNode*,int>> q;
        q.push_back({root, 1});
        while(!q.empty())
        {
            int sz = q.size();
            for(int i = 1; i<=sz; ++i)
            {
                auto pair = q.front();
                q.pop_front();
                if(pair.first->left)
                {
                    q.push_back({pair.first->left, pair.second*2});
                }
                if(pair.first->right)
                {
                    q.push_back({pair.first->right,pair.second*2+1});
                }
            }
            if(q.size() > 1)
            {
                max_width = max(max_width,q.back().second - q.front().second+1);
            }
        }
        return max_width;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值