[数据结构]二叉树

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值