1.构建和遍历二叉树
#include<iostream>
#include<stack>
using namespace std;
typedef struct node {
struct node *leftchild;
struct node *rightchild;
char data;
}BiTreeNode, *BiTree;
void CreateBiTree(BiTree &T) {
char c;
cin >> c;
if (c == '#')
T = NULL;
else {
T = new BiTreeNode;
T->data = c;
CreateBiTree(T->leftchild);
CreateBiTree(T->rightchild);
}
}
void travPre_I1(BiTree &T) {
if (!T) return;
cout << T->data;
travPre_I1(T->leftchild);
travPre_I1(T->rightchild);
}
void visitAlongLeftBranch(BiTree &T, stack<BiTree> &S) {
while (T) {
cout << T->data;
S.push(T->rightchild);
T = T->leftchild;
}
}
void travPre_I2(BiTree &T) {
stack<BiTree> S;
while (true) {
visitAlongLeftBranch(T, S);
if (S.empty()) break;
T = S.top();
S.pop();
}
}
int main() {
BiTree T;
CreateBiTree(T);
travPre_I1(T);
travPre_I2(T);
while (1);
return 0;
}
注意上述程序构建二叉树时,叶子节点必须写出来
例如想要构建如下的二叉树:
a
b c
d # # e
输入abd#c#e时不会得到正确的结果,而是要将上述结构转化成:
a
b c
d # # e
# # # #
必须知道叶子节点(即终点#)
2.有关二叉树的题目小结:
[剑指offer24] 二叉树的后序遍历序列
#include<iostream>
using namespace std;
bool VerifySequenceOfBST(int Sequence[], int length) {
int root = Sequence[length - 1];
//cout << root << endl;
int i = 0;
for (;i < length - 1;i++) {
if (Sequence[i] > root)
break;
}
int j = i;
for (;j < length - 1;j++) {
if (Sequence[j] < root)
//cout << (Sequence[i] < root) << endl;
return 0;
}
bool left = true;
if (i > 0)
left = VerifySequenceOfBST(Sequence, i);
bool right = true;
if (length - i > 0)
right = VerifySequenceOfBST(Sequence + i, length - i - 1);
return left&&right;
}
int main() {
int Input[] = {5,7,6,9,11,10,8};
cout << VerifySequenceOfBST(Input, 7) << endl;
while (1);
return 0;
}