算法学习 - 求二叉树的宽度

二叉树的宽度

二叉树的宽度定义为

  • 整个二叉树各层节点数,其中最大的值为这个二叉树的宽度。

所以二叉树的第一层就是1(根节点)。

代码实现(C++)

代码实现比较简单,树的遍历一般用递归比较方便。

//
//  main.cpp
//  TreeWidth
//
//  Created by Alps on 15/3/11.
//  Copyright (c) 2015年 chen. All rights reserved.
//
// achieve the binary tree width.

#include <iostream>
using namespace std;

#ifndef MAXDEEP
#define MAXDEEP 10 //定义树的最大深度
#endif

struct Node{ //定义树节点
    int val;
    struct Node * right;
    struct Node * left;
    Node(int v,Node* r,Node* l): val(v), right(r), left(l) {}
};

typedef Node* Tree;

int deepth = 0; //遍历的层
int width[MAXDEEP] = {0}; //存放各层宽度的数组

void TreeWidth(Tree t){
    if (t == NULL) {
        return;
    }
    if (deepth == 0) {
        width[0] = 1;
    }
    if (t->left != NULL) {
        width[deepth+1] += 1;
        deepth += 1;
        TreeWidth(t->left);
    }
    if (t->right != NULL) {
        width[deepth+1] += 1;
        deepth+=1;
        TreeWidth(t->right);
    }
    deepth-=1;
}

int main(int argc, const char * argv[]) {
    Node n1(1,NULL,NULL);
    Node n2(2,NULL,NULL);
    Node n3(3,NULL,NULL);
    Node n4(4,&n1,&n2);
    Node n5(5,&n3,NULL);
    Node n6(6,&n4,&n5);
    Tree t = &n6;
    TreeWidth(t);
    for (int i = 0; i < MAXDEEP; i++) {
        printf("%d ",width[i]);
    }
    // insert code here...
    std::cout << "Hello, World!\n";
    return 0;
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值