二叉树:前序、中序和后序遍历的方便记忆和应试非递归写法(考研)

前序遍历:

struct node {
	int val;
	node *left,*right; 
};
vector<int> preorder(node *root) {
	vector<int> res;
	if (!root) return res;
	stack<node*> st;
	auto p = root;
	while (p || st.size()) {
		if (p) {
			st.push(p);
			res.push_back(p->val);
			p = p->left;
		} else {
			auto top = st.top(); st.pop();
			p = top->right;
		}
	}
	return res;
}

中序遍历:

vector<int> inorder(node *root) {
	vector<int> res;
	if (!root) return res;
	auto p = root;
	stack<node*> st;
	while (p || st.size()) {
		while (p) {
			st.push(p);
			p = p->left;
		}
		p = st.top(); st.pop();
		res.push_back(p->val);
		p = p->right;
	}
	return res;
}

后序遍历:

vector<int> postorder(node *root) {
	vector<int> res;
	if (!root) return res; 
	stack<node*> st;
	auto p = root;
	node *tag;
	while (p || st.size()) {
		while (p) {
			st.push(p);
			p = p->left;
		}
		p = st.top(); st.pop();
		if (!p->right || p->right == tag) {
			res.push_back(p->val);
			tag = p;
			p = NULL; 
		} else {
			st.push(p);
			p = p->right;
		}
	}
	return res;
} 
发布了235 篇原创文章 · 获赞 51 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/ASJBFJSB/article/details/102946980
今日推荐