二叉树非递归后序(后根)遍历

1、要求

使用非递归方式对二叉树进行(后序)后根遍历。

2、思路

使用先序(先根)遍历,然后将遍历的结果反过来。但要注意:无论是先根遍历还是后根遍历,左子树的遍历始终在右子树之前,所以要使先根遍历结果反过来以后和后根遍历相同,在先根遍历时必须先遍历右子树。

3、代码

#include<iostream>
using namespace std;
#include<vector>
#include<stack>

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
private:
	vector<int> vecVal;
public:
	//递归方式
	/*
	vector<int> postorderTraversal(TreeNode *root) {
	TreeNode *p = root;
	if (p)
	{
	postorderTraversal(p->left);
	postorderTraversal(p->right);
	if (p->val)
	vecVal.push_back(p->val);
	}
	return vecVal;
	}
	*/

	//非递归
	vector<int> postorderTraversal(TreeNode *root) {
		vector<int> v;
		if (!root)return v;
		stack<TreeNode*> s;
		s.push(root);
		TreeNode *temp;
		while (!s.empty())
		{
			temp = s.top();
			v.push_back(temp->val);
			s.pop();
			if (temp->left)s.push(temp->left);
			if (temp->right)s.push(temp->right);
		}
		reverse(v.begin(), v.end());
		return v;
	}
};

猜你喜欢

转载自blog.csdn.net/ye1215172385/article/details/81056359