Use a special Binary Tree sequence to reconstruct a binary tree sequence.
There is no way to build a binary tree if we directly use the sequence of a binary tree, but it should be okay if it is a complete binary tree.
Here, the sequence uses-1 to indicate that the current node has no value.
The construction mainly uses non-recursive methods and queue, because the traversal of the sequence can be achieved through queue, so naturally we can also build through this method.
# Include <iostream> # include <queue> # include <stack> using namespace std; typedef struct Tree {Tree * left; Tree * right; int data; Tree () {data =-1; left = NULL; right = NULL;} Tree; void buildTree (int * A, int length, Tree * root) {if (NULL = root) | (0 = length) {return;} queue <Tree *> s; int I = 0; root-> data = A [0]; s. push (root); I ++; while ((! S. empty () & (I <length) {Tree * cur = s. front (); s. pop (); if (A [I]! =-1) & (I <length) {Tree * node = new Tree; node-> data = A [I]; cur-> left = node; s. push (node);} I ++; if (A [I]! =-1) & (I <length) {Tree * node = new Tree; node-> data = A [I]; cur-> right = node; s. push (node) ;} I ++ ;}; int main (void) {Tree * root = new Tree; // <define a root node int a [13] = {3, 5, 9, 2,-1,-1,-, 19,-1,-1 }; buildTree (a, 13, root); return 0 ;}
In addition, there are some ways to pass in user input to build any binary tree.
Void CreateBiTree (BiTNode ** root) // second-level pointer as function parameter {char ch; // scanf ("\ n % c", & ch) of data to be inserted ); // cin> ch; if (ch = '#') * root = NULL; else {* root = (BiTNode *) malloc (sizeof (BiTNode )); (* root)-> data = ch; printf ("Enter % c's left child:", ch); CreateBiTree (& (* root)-> lchild )); printf ("Enter the right child of % c:", ch); CreateBiTree (& (* root)-> rchild ));}}
In addition, the previous section describes how to build by combining the forward, backward, and middle order. For more information, see
Http://blog.csdn.net/xietingcandice/article/details/42557839