Algorithm learning-Finding the width of a binary tree

Source: Internet
Author: User

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, &AMP;N1,&AMP;N2); Node N5 (5, &n3,NULL); Node N6 (6, &AMP;N4,&AMP;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.