题解 | #二叉树遍历#

二叉树遍历

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

}


全部评论

相关推荐

05-28 12:43
已编辑
天津中德应用技术大学 Java
给个offer吧😭...:现在27都结束了,28都开始了。还要1k人啊。更别说你这个bg,现在92都不一定随便进1k人的(除了外包)。只能和我一样海投了,社招也投
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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