zl程序教程

您现在的位置是:首页 >  后端

当前栏目

二叉树遍历(前序、中序、后序)stack

二叉树遍历 Stack 中序 后序 前序
2023-09-11 14:19:17 时间
//====================先序遍历=======================
class Solution {
	public:
		vector<int> res;
		stack<TreeNode*> st;
		while (root) {
			res.push_back(root->val);
			st.push(root);
			root = root->left;
		}
		while (!st.empty()) {
			auto node = st.top();
			st.pop();
			node = node->right;
			while (node) {
				res.push_back(node->val);
				st.push(node);
				node = node->left;
			}
		}
		return res;
};

//====================中序遍历=======================
class Solution {
	public:
		vector<int> res;
		stack<TreeNode*> st;
		while (root) { 
				st.push(root);
				root = root->left;
		}
		while (!st.empty()) {
				auto node = st.top();
				st.pop();
				res.push_back(node->val);
				node = node->right;
				while (node) {
					st.push(node);
					node = node->left;
				}
		}
		return res;
};

//====================后序遍历=======================
class Solution {
	public:
		stack<TreeNode*>st;
		vector<int>a;
		if (root == nullptr) return a;		//判断必须加,不然提交报错
		st.push(root);
		while (!st.empty())
		{
			root = st.top();
			st.pop();
			a.push_back(root->val);
			if (root->left) st.push(root->left);
			if (root->right) st.push(root->right);
		}
		reverse(a.begin(), a.end());			//转换!!!
		return a;
};