LintCode 1101 给定一颗二叉树, 编写一个函数求该树的最大宽度, 即该树每一层的宽度的最大值. 该二叉树具有与满二叉树相同的结构, 但是一些节点为空 null. 注

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the root
     * @return: the maximum width of the given tree
     */
    int widthOfBinaryTree(TreeNode * root) {
        // Write your code here
        if(root==NULL) return 0;
        vector<TreeNode*> node;
        vector<int> layernum;
        vector<int> pos;
        vector<int> Front,Back;
        int front=0;
        node.push_back(root);
        layernum.push_back(0);
        pos.push_back(1);
        Front.push_back(1);
        while(node.size()-front>0){
            if(front!=0&&layernum[front]!=layernum[front-1]){
                Back.push_back(pos[front-1]);
                Front.push_back(pos[front]);
            }
            if(node[front]->left!=NULL){
                node.push_back(node[front]->left);
                layernum.push_back(layernum[front]+1);
                pos.push_back(pos[front]*2);
            }
            if(node[front]->right!=NULL){
                node.push_back(node[front]->right);
                layernum.push_back(layernum[front]+1);
                pos.push_back(pos[front]*2+1);
            }
            front++;
        }
        Back.push_back(pos[front-1]);
        int max;
        max=Back[0]-Front[0]+1;
        for(int i=0;i<Front.size();i++){
            max=max>Back[i]-Front[i]+1?max:Back[i]-Front[i]+1;
        }
        return max;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值