二叉树的前序、中序、后序遍历(题中强制要求用迭代算法,不能用递归)

在这里插入图片描述

class Solution {
public:
	vector<int> preorderTraversal(TreeNode* root) {
		vector<int>res;
		if (root == NULL)return res;

		stack<TreeNode*>s;
		TreeNode*cur = root;
		while (cur != NULL || !s.empty())
		{
			while (cur != NULL)
			{
				res.push_back(cur->val);
				s.push(cur);
				cur = cur->left;
			}
			TreeNode*top = s.top();//此时该结点的左子树已经全部遍历完了(该结点无左子树)
			s.pop();
			cur = top->right;//对右子树遍历
		}
		return res;

	}
};

在这里插入图片描述
递归:

class Solution {
public:
	vector<int> inorderTraversal(TreeNode* root) {
		DFS(root);
        return res;
	}
    void DFS(TreeNode* root)
    {
        if(root==NULL)return;
        DFS(root->left);//完成了当前结点的左子树的遍历
        res.push_back(root->val);
        DFS(root->right);//继续完成当前结点的右子树的遍历
    }
 private:
    vector<int>res;
};

迭代:

class Solution {
public:
	vector<int> inorderTraversal(TreeNode* root) {
		vector<int>res;
		if (root == NULL)return res;

		stack<TreeNode*>s;
		TreeNode*cur = root;
		while (cur != NULL || !s.empty())
		{
			while (cur != NULL)
			{

				s.push(cur);
				cur = cur->left;
			}
			TreeNode*top = s.top();//此时该结点的左子树已经全部遍历完了
			res.push_back(top->val);
			s.pop();
			cur = top->right;//对右子树遍历
		}
		return res;

	}
};

在这里插入图片描述
思路:参照前序遍历,先变成根右左,再逆序输出即可变为后序的左右根!
迭代:

class Solution {
public:
	vector<int> postorderTraversal(TreeNode* root) {//先变成根右左,再逆序输出即可变为后序的左右根
		vector<int>res;
		if (root == NULL)return res;

		stack<TreeNode*>s;
		stack<TreeNode*>temp_s;
		TreeNode*cur = root;
		while (cur != NULL || !s.empty())
		{
			while (cur != NULL)
			{
				temp_s.push(cur);
				s.push(cur);
				cur = cur->right;
			}
			TreeNode*top = s.top();//此时该结点的右子树已经全部遍历完了(该结点无右子树)
			s.pop();
			cur = top->left;//对左子树遍历
		}
		while (!temp_s.empty())
		{
			res.push_back(temp_s.top()->val);
			temp_s.pop();
		}
		return res;

	}
};

递归:

class Solution {
public:
	vector<int> postorderTraversal(TreeNode* root) {
		DFS(root);
        return res;
	}
    void DFS(TreeNode* root)
    {
        if(root==NULL)return;
        DFS(root->left);//完成了当前结点的左子树的遍历
        DFS(root->right);//继续完成当前结点的右子树的遍历
        res.push_back(root->val);
    }
 private:
    vector<int>res;
};
发布了212 篇原创文章 · 获赞 4 · 访问量 8786

猜你喜欢

转载自blog.csdn.net/ShenHang_/article/details/104784165