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