标签:
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?
#include<iostream>
#include<vector>
#include<stack>
#include<list>
using namespace std;
//二叉树的定义
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//采用递归的方法来做:
void post_search(TreeNode* root,vector<int>& vec)
{
if(root==NULL)
return;
post_search(root->left,vec);
post_search(root->right,vec);
vec.push_back(root->val);
return;
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> last_result;
post_search(root,last_result);
return last_result;
}
/*
这道题目是“二叉树的后序遍历”。通常有两种做法,递归求解以及循环求解。
递归求解,较为简单,先访问左孩子结点、在访问右孩子节点,访问当前节点。
详细可参照如下代码。
循环求解,较为麻烦。但是相对于递归求解而言,这种方法耗费的函数栈空间更小,
并且省去了大量的函数调用时间的开销,速度更加快,
*/
//采用堆栈的方法来做
vector<int> postorderTraversal(TreeNode *root)
{
stack<TreeNode*> temp;
vector<int> result_last;
TreeNode* temp_node;
temp.push(root);
while
}
int main()
{
system("psuse");
return 1;
}
leetcode——Binary Tree Postorder Traversal(递归,栈)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4423519.html