提交 ac6c24d6 编写于 作者: 东方怂天's avatar 东方怂天

Add extention about how to creat a binary tree from pre-order & in-order.

上级 fddcbdd3
#pragma once
//Include Liberary.
#include <iostream>
#include <stack>
......@@ -42,11 +44,58 @@ void CreatBiTree_Rec(BiTree &root)
//Loop to creat binary tree.
void CreatBiTree_Loop(BiTree &root)
{
char c;
stack<BiTree> BiStack;
while (true)
root = new BiNode;
BiNode *p = root;
bool IsRight = false;
//Define a pointer to do many thing.
p->data = getchar();
//Push in.
BiStack.push(p);
while (c = getchar())
{
switch (c)
{
case '#':
//If null stack then end.
if (BiStack.empty())
{
return;
}
//pB revoke.
p = BiStack.top();
BiStack.pop();
IsRight = true;
break;
default:
if (IsRight)
{
p->RightChild = new BiNode;
p = p->RightChild;
}
else
{
p->LeftChild = new BiNode;
p = p->LeftChild;
}
//Tag the pB.
p->data = c;
p->LeftChild = p->RightChild = NULL;
//Push in.
BiStack.push(p);
IsRight = false;
break;
}
}
return;
}
enum Type
......
#pragma once
#include "BinaryTree.h"
#include <string>
void UnionPreIn(string Pre, string In, BiTree &root)
{
//Pre order:ABDECFGH
//In order:DEBAGFCH
root = new BiNode;
root->data = Pre[0];
string left, right;
int rootPos = In.find(Pre[0]);
left = In.substr(0, rootPos);
right = In.substr(rootPos + 1, In.length());
int lLength = left.length();
int rLength = right.length();
root->LeftChild = root->RightChild = NULL;
if (lLength != 0)
{
cout << "LEFT" << endl;
cout << '\t' << Pre.substr(1, lLength) << " " << left << endl;
root->LeftChild = new BiNode;
cout << root->data << "l" << Pre.substr(1, lLength)[0] << endl;
root->LeftChild->data = Pre.substr(1, lLength)[0];
UnionPreIn(Pre.substr(1, lLength), left, root->LeftChild);
}
if (rLength != 0)
{
cout << "RIGHT" << endl;
cout << '\t' << Pre.substr(Pre.length() - rLength, Pre.length()) << " " << right << endl;
root->RightChild = new BiNode;
cout << root->data << "r" << Pre.substr(Pre.length() - rLength, Pre.length())[0] << endl;
root->RightChild->data = Pre.substr(Pre.length() - rLength, Pre.length())[0];
UnionPreIn(Pre.substr(Pre.length() - rLength, Pre.length()), right, root->RightChild);
}
}
\ No newline at end of file
#include "BinaryTree.h"
#include "Extention.h"
int main()
{
......@@ -8,8 +9,11 @@ int main()
//Pre order:ABDECFGH
//In order:DEBAGFCH
//Post order:EDBGFHCA
/*
cout << "Input ebt:" << endl;
CreatBiTree_Rec(root);
//CreatBiTree_Rec(root);
CreatBiTree_Loop(root);
cout << "Pre order:" << endl;
DisplayBiTree_Stack(root, Pre);
......@@ -28,6 +32,15 @@ int main()
cout << endl;
DisplayBiTree(root, Post);
cout << endl;
*/
UnionPreIn("ABDECFGH", "DEBAGFCH", root);
cout << endl;
DisplayBiTree(root, Pre);
cout << endl;
DisplayBiTree(root, In);
cout << endl;
DisplayBiTree(root, Post);
cout << endl;
return 0;
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册