The width of the binary tree
The width of the binary tree is defined as
- The total number of nodes across the binary tree, where the maximum value is the width of the binary tree.
So the first layer of the binary tree is 1 (root node).
Code implementation (c + +)
Code implementation is relatively simple, the traversal of the tree is generally more convenient recursive.
////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//define the maximum depth of the tree#endifstructnode{//define tree nodes intValstructNode * RIGHT;structNode * LEFT; Node (intv,node* r,node* L): Val (v), right (R), left (l) {}};typedefnode* Tree;intDeepth =0;//traversed layerintWidth[maxdeep] = {0};//storing arrays of each layer widthvoidTreewidth (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;}intMainintargcConst 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(inti =0; i < Maxdeep; i++) {printf ("%d", Width[i]); }//Insert code here ...Std::cout <<"Hello, world!\n.";return 0;}
Algorithm learning-Finding the width of a binary tree