码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-03-11 19:45:34      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:二叉树   宽度   c++   

二叉树的宽度

二叉树的宽度定义为

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

所以二叉树的第一层就是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;
}

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

标签:二叉树   宽度   c++   

原文地址:http://blog.csdn.net/alps1992/article/details/44202355

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!