leetcode:二叉樹之Binary Tree Postorder Traversal

leetcode:二叉樹之Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes’ values.

For example: 

Given binary tree {1,#,2,3},

   1
     \
      2
     /
    3
return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

即,二叉樹後序遍歷。

c++實現:

#include <iostream>
#include <vector>
#include <malloc.h>
#include <stack>

using namespace std;
struct TreeNode 
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) { }
};
void CreateBiTree(TreeNode* &T)
{
	char ch;
	cin>>ch;

	if(ch=='#') 
		T=NULL;
	else
	{
		T = (TreeNode*)malloc(sizeof(TreeNode));
		if(!T) exit(0);
		T->val = ch-'0';
		CreateBiTree(T->left);  
		CreateBiTree(T->right); 
	}
}
vector<int> postorderTraversal(TreeNode *root)
{
	vector<int> result;
	/* p,正在訪問的結點,q,剛剛訪問過的結點*/
	const TreeNode *p, *q;
	stack<const TreeNode *> s;
	p = root;
	do {
		while (p != NULL) /* 往左下走*/
		{ 
			s.push(p);
			p = p->left;
		}
		q=NULL;
		while (!s.empty()) 
		{
			p = s.top();
			s.pop();
			/* 右孩子不存在或已被訪問,訪問之*/
			if (p->right == q) 
			{
				result.push_back(p->val);
				q = p; /* 保存剛訪問過的結點*/
			} else {
				/* 當前結點不能訪問,需第二次進棧*/
				s.push(p);
				/* 先處理右子樹*/
				p = p->right;
				break;
			}
		}
	} while (!s.empty());
	return result;
}
int main()
{
	TreeNode* root(0);
	CreateBiTree(root);

	cout<<"輸出後序遍歷結果:"<<endl;
	vector<int> v;
	v=postorderTraversal(root);
	for(int i = 0;i < v.size();i++)
        cout<<v[i];
	cout<<endl;
    
	return 0;
}

測試結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章