题解 | #二叉树遍历#

二叉树遍历

https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef

先序遍历字符串而不是二叉树的先序遍历
#include<iostream>
using namespace std;


struct TreeNode {
	char data;
	TreeNode* leftchild;
	TreeNode* rightchild;
};

int index=0;

TreeNode* Preorder(string str) {
	char c = str[index++];
	if (c == '#') return NULL;
	else {
		TreeNode* p = new TreeNode;  //申请一个新结点
		p->data = c;
		p->leftchild = Preorder(str);
		p->rightchild = Preorder(str);
		return p;

	}
}

void inorder(TreeNode* t) {
	if (t == NULL) {
		return;
	}
	else{
		inorder(t->leftchild);
		cout << t->data << ' ';
		inorder(t->rightchild);
		return ;
	}
}


int main() {
	string str;
	while (cin >> str) {
		TreeNode *root = Preorder(str);  //建树并且拿到初始结点
		inorder(root);
	}

}


全部评论

相关推荐

10-14 21:00
门头沟学院 Java
吃花椒的狸猫:这个人说的倒是实话,特别是小公司,一个实习生哪里来的那么多要求
点赞 评论 收藏
分享
10-20 11:11
辽宁大学 营销
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务