C++编程学习之LeetCode OJ

Binary Tree Postorder Traversal:
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3

return [3,2,1].

#include<iostream>
#include<vector>
#include<stack>
#define NUM 2
using namespace std;
struct TreeNode{
int val;
TreeNode *left; 
TreeNode *right;
};
class Solution{
public:
	vector<int> postorderTraversal(TreeNode *root)
	{
		vector<int> data;
		stack<TreeNode*> stk;
		while(root!=NULL||!stk.empty())
		{
			if(root)
			{	
				while(root)
				{
					data.push_back(root->val);
					stk.push(root);
					root=root->right;
				}		
			}
			else
			{
				root=stk.top()->left;
				stk.pop();
			}
		}
		reverse(data.begin(),data.end());
		return data;

	}
};
int main()
{
	TreeNode tree[NUM],*root=NULL,*next=NULL,*head=NULL;
	Solution s;
	vector<int> ans;
	int i;
	for(i=0;i<NUM;i++)
	cin>>tree[i].val;
	root=new TreeNode;
	root->val=tree[0].val;
	head=root;
	i=1;
	while(i<NUM)
	{
		next=new TreeNode;
		root->left=next;
		root->right=NULL;
		next->val=tree[i].val;
		root=next;
		i++;
	}
	root->left=root->right=NULL;
	root=head;
	ans=s.postorderTraversal(root);
	vector<int>::iterator it=ans.begin();
	while(it!=ans.end())
	{cout<<*it<<"\n";it++;}	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值