postorder遍历二叉树,参考http://blog.csdn.net/feliciafay/article/details/18341703
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode *> s;
if (root == NULL) return res;
s.push(root);
TreeNode *cur = root;
TreeNode *pre = NULL;
while (!s.empty()) {
cur = s.top();
if ((cur->left == NULL && cur->right == NULL) || ((pre != NULL) && (pre == cur->left || pre == cur->right))) {//叶子节点才输出本节点,不然现输出子节点
//
res.push_back(cur->val);
s.pop();
pre = cur; // 在pop了cur之后才更新pre
}
else {
if (cur->right != NULL) {
s.push(cur->right);
}
if (cur->left != NULL) {
s.push(cur->left);
}
}
}
return res;
}
};