文章

10

粉丝

0

获赞

18

访问

551

头像
二叉树的建立和遍历 题解:
P1109 同济大学机试题
发布于2026年2月22日 17:38
阅读数 49

#include <iostream>
#include <string>
using namespace std;

struct TNode{
	char data;
	TNode *lchild,*rchild;
};

int index=0;

TNode* CreateTree(const string &s)
{
	if(index>=s.size()) return nullptr;
	else if(s[index]=='0'){index++;return nullptr;}
	else{
	TNode* n=new TNode();
	n->data=s[index++];
	n->lchild=CreateTree(s);
	n->rchild=CreateTree(s);
	return n;
	}
}

void preorder(TNode *root)
{
	if(root==nullptr) return;
	cout<<root->data<<' ';
	preorder(root->lchild);
	preorder(root->rchild);
}

void inorder(TNode *root)
{
	if(root==nullptr) return;
	inorder(root->lchild);
	cout<<root->data<<' ';
	inorder(root->rchild);
}

void postorder(TNode *root)
{
	if(root==nullptr) return;
	postorder(root->lchild);
	postorder(root->rchild);
	cout<<root->data<<' ';
}

void leaf(TNode *root)
{
	if(root==nullptr) return;
	if(root->lchild==nullptr&am...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发