递归方法:
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> list; if(root == NULL) return list; postorder(root, list); return list; } void postorder(TreeNode *root, vector<int> &list) { if(root->left != NULL) postorder(root->left, list); if(root->right != NULL) postorder(root->right, list); list.push_back(root->val); } };
/** * Definition for binary tree * 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> list; if(root == NULL) return list; stack<TreeNode *> s; s.push(root); TreeNode *pre = NULL; while(!s.empty()) { TreeNode *now = s.top(); if((now->left == NULL && now->right == NULL) || ((pre!=NULL)&&(now->right==pre)) || ((pre!=NULL)&&(now->right==NULL)&&(now->left==pre))) { list.push_back(now->val); pre = now; s.pop(); continue; } if(now->left != NULL && now->left != pre) { s.push(now->left); continue; } if(now->right != NULL) { s.push(now->right); continue; } } return list; } };