どのように直感的なプリントバイナリツリーを学ぶための20のアルゴリズム
アルゴリズムの考え方
- 印刷方法は、ツリーの出力処理シーケンスを実行されます
- 実際には、グラフィックス出力の問題の出力は、ここではあまり精緻化を行うことではありません。
- 用途sstream提供コンテンツライブラリ関数
:/ *ライブラリは、三種類の定義
* istringstream、及びにstringstreamのostringstream、入力ストリームのために使用され、そして出力入出力動作を制御します。
1.stringstream :: STR *();ストリームのオブジェクト現在の内容のAのコピーとA Stringを返します。
(文字列&Sのconst)* :: 2.stringstream STR;内容のASザ・S・セットは、ストリーム、任意の破棄前。目次
* 3.stringstreamは、にstringstream Sを空にし、s.str( "");
*変換4.任意のタイプを実現
*
*にstringstreamストリームを、
ストリーム<< T; //ストリームに値を渡す
out_type結果; //ここで結果保存
ストリーム>>結果を; //書き込み値をもたらすこと
*
*
int main(){
string s = "1 23 # 4";
stringstream ss;
ss<<s;
while(ss>>s){
cout<<s<<endl;
int val = convert<int>(s);
cout<<val<<endl;
}
return 0;
} * /
プログラムコード:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Node
{
public:
Node(int data)
{
value = data;
left = NULL;
right = NULL;
}
public:
int value;
Node *left;
Node *right;
};
/*Root为根节点,Height为当前处于二叉树的那一层(从0层开始);
* String为根、左、右节点的区分符号;
* len为格式化打印参数,固定为17,
* 即每个节点都将占有17个字符的位置*/
void printInorder(Node *Root, int Height, string String, int Len)
{
if(NULL == Root)
return ;
printInorder(Root->right, Height + 1, "v", Len);//先打印右子树
//打印跟节点
stringstream ss;
/*<sstream>库定义了三种类:
* istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。
* 1.stringstream::str(); returns a string object with a copy of the current contents of the stream.
* 2.stringstream::str (const string& s); sets s as the contents of the stream, discarding any previous contents.
* 3.stringstream清空,stringstream s; s.str("");
* 4.实现任意类型的转换
*
* stringstream stream;
stream<<t;//向流中传值
out_type result;//这里存储转换结果
stream>>result;//向result中写入值
*
*
int main(){
string s = "1 23 # 4";
stringstream ss;
ss<<s;
while(ss>>s){
cout<<s<<endl;
int val = convert<int>(s);
cout<<val<<endl;
}
return 0;
}*/
ss << Root->value;
string val = String + ss.str() + String; //构造H*H或v*v或^*^
int LenString = val.length();// 总长度
int Lenleft = (Len - LenString) / 2;// 1/2的长度
int Lenright = Len - LenString - Lenleft;//右距离
val = string(Lenleft, ' ') + val + string(Lenright, ' ');
cout << string(Height * Len, ' ') << val << endl;
printInorder(Root->left, Height + 1, "^", Len);
return ;
}
void PrintTree(Node *Root)
{
cout << "Binary Tree:" << endl;
printInorder(Root, 0, "H", 17);
cout << endl;
}
void CreatTree(Node **head, int *Array, int Len, int Index)
{
if(Index > Len - 1 || -1 == Array[Index] )
return;
(*head) = new Node(Array[Index]);
CreatTree(&((*head)->left), Array, Len, 2 * Index + 1);
CreatTree(&((*head)->right), Array, Len, 2 * Index + 2);
}
int main()
{
int Array[] = {1,2,3,4,-1,5,6,-1,7};
Node *Root = NULL;
CreatTree(&Root, Array, 9, 0);
PrintTree(Root);
return 0;
}
結果は以下の通りであります:
Binary Tree:
v6v
v3v
^5^
H1H
^2^
v7v
^4^
最後の記事では、私はあなたにすべての幸せなランタンフェスティバルを願っています。