Title Description:
implements a function to print a binary tree by its glyph, that is, the first line prints from left to right, the second layer prints from right to left, the third line prints from left to right, and so on.
Analysis:
for an n-tier two-fork tree, you can use an array to record the two-ary tree in sequence, specifically to separate each layer explicitly, filling the front n-1 layer of the two fork tree. The method is that, for a null node, if there are non-null nodes after it, then the child node position is padded with null until all positions are traversed, and then the binary tree is printed in sequence, and the subscript of each layer's end element is 2^n-2 (the number of elements in the first n layer is 2^n-1, So its subscript is 2^n-2).
Vector<vec<int>> Printtree (Node *tree) {vector<vector<node*>> ret;
Vector<int> num;
vector<vector<int>> result;
if (tree = = NULL) return result;
Ret.push_back (tree);
int len = 0;
int lastlocal = 0; while (Len < Ret.size ()) {if (Ret[len]! = NULL) {ret.push_back (ret[len]->left);//if (ret
[Len]->left! = NULL)//lastlocal = len*2+1;
Ret.push_back (Ret[len]->right);
if (ret[len]->right! = NULL)//lastlocal = len*2+2; }else{//fill the front n-1 layer of the two fork tree with the IF (! Allisnull (ret, len)) {//Use a function to determine if there is a non-null node after the second node//each call function to determine that there will be repeated traversal,//The workaround is to maintain a lastlocal value to record the current last
The subscript for a non-null node//each time only needs to determine if Len is less than lastlocal.
if (Len < Lastlocaol) Ret.push_back (NULL);
Ret.push_back (NULL);
}} len++; } int i = 0;
n = 1; BOOL FLAGE = true;
while (I < ret.size ()) {if (flage) {//positive-order printing num.clear ();
int tmp = POW (2, N)-2; for (int j = i; J <= Minnum (TMP, Ret.size ()-1); J + +) {if (ret[j]! = NULL) Num.push_ba
CK (Ret[j]->val);
} i = Minnum (tmp, Ret.size ()-1) + 1;
if (num.size () > 0) result.push_back (num);
Flage = false;
n + = 1;
}else{//Reverse-order print num.clear (); for (int j = minnum (Pow (2, N)-2, Ret.size ()-1); J >= i; j--) {if (ret[j]! = NULL) num
. push_back (Ret[j]->val);
} if (Num.size () > 0) result.push_back (num);
i = Minnum (POW (2, N)-2, Ret.size ()-1);
Flage = true;
n + = 1;
}} return result;
} int Minnum (int a, int b) {return (a < b)? A:b;} BOOL Allisnull (vector<node*>& ret, inT len) {//Determine if there are no non-null nodes for (int i = len + 1; i < ret.size (); i++) {if (Ret[i]! = NULL) Retu
RN false;
} return true; }