Build a fully binary tree, console print binary tree

Source: Internet
Author: User

Two more practical code, one for building a complete binary tree based on the input array, one for printing binary tree in the console, easy to view the structure of the tree (the code to print the binary tree is found on the Internet, now can not find the source, to the author sorry).

//the first is the structure of the nodestructTreeNode {intVal; structTreeNode *Left ; structTreeNode *Right ; TreeNode (intx): Val (x), left (null), right (null) {}};///build a full binary tree and use the queueTreeNode * Constructtree (intArr[],intlength) {    if(Length <=0)returnNULL; List<TreeNode*>nodeList; TreeNode*root =NewTreeNode (arr[0]);    Nodelist.push_back (root);  for(inti =1; i < length; i++) {TreeNode*node =NewTreeNode (Arr[i]);  while(!Nodelist.empty ()) {TreeNode*top =Nodelist.front (); if(!top->Left ) {Top->left =node;                Nodelist.push_back (node);  Break; }            Else if(!top->Right ) {Top->right =node;                Nodelist.push_back (node);  Break; }            ElseNodelist.pop_front (); }    }    returnRoot;}
//print binary tree, using the method of first order traversalvoidPrinttree (TreeNode *root,intBlk =0){    if(Root = =NULL)return;  for(inti =0; I < BLK; i++) printf ("    ");//Indent inprintf"|-<%d>\n", Root->val);//print "|-<id>" formPrinttree (Root->left, Blk +1);//print subtree, accumulate indent countPrinttree (root->right, Blk +1);//print subtree, accumulate indent count}

Build a fully binary tree, console print 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.